A couple of points:
- if you use the
TextChanged
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. the
Validated
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 a
FormatException
- "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();
}