如何在Total textbox中添加文本框值并获得总和?
问题描述:
这里我有10个文本框。当我在文本框中输入金额而没有任何按钮时,单击文本框的总和值将显示在Totaltextbox中。我的代码是
Here i have 10 textboxes.when i enter the amount in textboxes with out any button clicking the sum of textboxes value will be display in Totaltextbox. my code is
protected void txtrent_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtrent.Text) && !string.IsNullOrEmpty(txtmain.Text))
txttotal.Text = (Convert.ToInt32(txtrent.Text) + Convert.ToInt32(txtmain.Text)).ToString();
}
这只适用于两个文本框。当我这样编写代码时会很大。所以请帮我用简单的代码完成这个操作
This is for two textboxes only.when i write like this the code will be huge.so pls help me how to do this with simple code
答
您可以使用foreach
循环遍历表单上的所有控件并选择其中的内容文本框,随时累积值。但是,您不应在文本字段上使用Convert.ToInt32
,因为您无法保证它们包含有效数据。使用TryParse
以便捕获任何错误。
You can use aforeach
loop to iterate through all the controls on your form and select the contents of the textboxes, accumulating the values as you go. However, you should not useConvert.ToInt32
on text fields because you cannot guarantee that they contain valid data. UseTryParse
so you can catch any errors.
使用单个处理程序的按键事件。
例如
Use the key down event with a single handler.
For e.g.
Text1_KeyDown += sumHandler;<br />
Text2_KeyDown += sumHandler;
...
等等。
在sumHandler中,将所有文本框汇总并显示在总文本框中。 />
...
and so on.
In they sumHandler, sum all the text boxes and display in the total textbox.
void sumHandler(Control c,Event e)
{
txtTotal = Convert.ToInt(Text1.Text) + Convert.ToInt(Text2.Text) + ... Convert.ToInt(Text10.Text)
}
在我看来,您可以通过多种方式进行此操作。
案例:
You can do it in multiple ways in my opinion.
A case:
foreach (Control c in this.Controls)
{
if (c is TextBox) // or, c.GetType() == typeof(Textbox)
{
int value = 0;
if(int.TryParse(((TextBox)c).Text,out value))
totalValue += value;
}
}
totalTextbox.Text = totalValue;
其他:
从多个文本框中添加值并显示总和 [ ^ ]
如何使用文本框计算并跳过空文本框? [ ^ ]