如何在Total textbox中添加文本框值并获得总和? [英] How to add textboxes values and get sum in Total textbox?

查看:66
本文介绍了如何在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 a foreach 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 use Convert.ToInt32 on text fields because you cannot guarantee that they contain valid data. Use TryParse 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;



其他:

从多个文本框中添加值并显示总和 [ ^ ]

如何使用文本框计算并跳过空文本框? [ ^ ]


这篇关于如何在Total textbox中添加文本框值并获得总和?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆