Click here to Skip to main content
15,894,646 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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());

C#
private void txt_TextChanged(object sender, EventArgs e)
         {
            txt_Total.Text = (Convert.ToInt32(txt_item1.Text) + Convert.ToInt32(txt_Item2.Text)).ToString();            
        }
Posted

1 solution

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
C#
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
C#
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();
}
 
Share this answer
 
Comments
Sascha Lefèvre 29-May-15 7:12am    
+5

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900