简体   繁体   English

如何使用Textbox将值接受到数组中并使用Button显示数字的总和?

[英]How to accept values into array using Textbox and display the Sum of numbers using a Button?

I have three TextBoxes and a Button. 我有三个TextBox和一个Button。 I should be able to enter multiple numbers on the TextBoxes. 我应该能够在TextBoxes上输入多个数字。 When I click on the Button, the sum of the numbers should be displayed on another TextBox. 当我单击按钮时,数字的总和应该显示在另一个TextBox上。 How to accept values into array using Textbox and display the Sum of numbers using a Button? 如何使用Textbox将值接受到数组中并使用Button显示数字的总和?

You could do something like the following: 您可以执行以下操作:

 int[] numbers = new int[2];  // Declare the array 

 public void Button1_Click() {
    numbers[0] = Int32.Parse(TextBox1.Text);
    numbers[1] = Int32.Parse(TextBox2.Text);
    numbers[2] = Int32.Parse(TextBox3.Text);

    TextBox4.Text = numbers.Sum().ToString();
 }

Note: You probably want to add some error handling into the application to ensure that the textbox values are indeed numbers. 注意:您可能希望在应用程序中添加一些错误处理,以确保文本框值确实是数字。 Also use TryParse rather than the standard Parse . 也可以使用TryParse而不是标准Parse

您可以使用一些单独的例如逗号,然后将您的Textbox值拆分为获取字符串数组,然后您可以尝试将字符串解析为int或decimal。然后计算总和

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM