如何在没有点击按钮的情况下在第三个文本框中获取两个文本框总和?
您好,
您好我的项目使用三个文本框一个是txt_Item1,txt_Item2和txt_Total
当我输入txt_Item1和txt_Item2所以我想要显示值在没有按钮点击的txt_Total中。
我在txt_Item2的文本更改事件中使用下面的代码。
总计即将到来,但每当我更改Item2的值并且如果我更改Item1的值总和没有自动反映。
command.Parameters.AddWithValue(@ Total,txt_Total.Text =(Convert.ToInt32(txt_item1.Text)+ Convert.ToInt32(txt_Item2.Text )。ToString());
Hello,
hi in my project am using three text boxes one is txt_Item1, txt_Item2 and txt_Total
when i enter in txt_Item1 and txt_Item2 so i want to display value in txt_Total without button click.
Am using this below code on text changed event of txt_Item2 .
Total is coming but whenever I change the value of Item2 and If I change the value of Item1 the total is not reflecting Automatically.
command.Parameters.AddWithValue("@Total", txt_Total.Text = (Convert.ToInt32(txt_item1.Text) + Convert.ToInt32(txt_Item2.Text)).ToString());
private void txt_TextChanged(object sender, EventArgs e)
{
txt_Total.Text = (Convert.ToInt32(txt_item1.Text) + Convert.ToInt32(txt_Item2.Text)).ToString();
}
几点:
- 如果您使用TextChanged
事件,那么您将尝试使用文本框中的每个击键进行计算 - 即在用户完成输入之前。我个人会选择在用户完成输入后触发的事件,例如验证
事件
- 通过使用Convert.ToInt32,您假设两个文本框都已填充且肯定包含数字。如果尚未填充txt_Item2,则会抛出FormatException
- 输入字符串格式不正确。你最好使用 int.TryParse [ ^ ] - 请参阅此CP文章了解更多细节 Int32.Parse(),Convert.ToInt32之间的差异( )和Int32.TryParse() [ ^ ]
此代码有效
A couple of points:
- if you use theTextChanged
event then you will be attempting to do the calculation with every keystroke in the textboxes - i.e. before the user has finished typing. I personally would choose an event that is fired once the user has completed their input e.g. theValidated
event
- By using Convert.ToInt32 you are assuming that both textboxes are populated and definitely contain numbers. If txt_Item2 has not been populated then this will throw aFormatException
- "Input String was not in a correct format". You are better off using int.TryParse[^] - see this CP article for more detail Difference Between Int32.Parse(), Convert.ToInt32(), and Int32.TryParse()[^]
This code works
private void textBox1_Validated(object sender, EventArgs e)
{
CalcTotal();
}
private void textBox2_Validated(object sender, EventArgs e)
{
CalcTotal();
}
private void CalcTotal()
{
int i, j;
if(int.TryParse(textBox1.Text, out i) && int.TryParse(textBox2.Text, out j))
textBox3.Text = (i + j).ToString();
}
或者您可以更有效地执行此操作,例如
Or you can do it a little more efficiently like this
public Form1()
{
InitializeComponent();
this.textBox1.Validated += new System.EventHandler(this.CalcTotal);
this.textBox2.Validated += new System.EventHandler(this.CalcTotal);
}
private void CalcTotal(object sender, EventArgs e)
{
int i, j;
if(int.TryParse(textBox1.Text, out i) && int.TryParse(textBox2.Text, out j))
textBox3.Text = (i + j).ToString();
}