简体   繁体   中英

Add values from two textboxes and display the sum in third textbox 3 but value of 1st aor 2nd textbox show in third textbox

enter image description here

Add values from two textboxes and display the sum in third textbox 3 but value of 1st aor 2nd textbox show in third textbox

TextBox3.Text = Convert.ToDouble(TextBox1.Text) + Convert.ToDouble(TextBox2.Text)

This will do it, just enter proper number. No exception handled.

To handle exception, use Double.TryParse instead of Convert.ToDouble .

Look at msdn example.

This will automatically change your value once you alter textbox1's value

private void textBox1_TextChanged(object sender, EventArgs e)
    {
        if (textBox1.Text.Length > 0 && textBox2.Text.Length > 0)
        {
            textBox3.Text = Convert.ToString(Convert.ToDouble(textBox1.Text) + Convert.ToDouble(textBox2.Text));
        }
        if (textBox1.Text.Length > 0 && textBox2.Text.Length == 0)
        {
            textBox3.Text = textBox1.Text;
        }
        if (textBox1.Text.Length == 0 && textBox2.Text.Length > 0)
        {
            textBox3.Text = textBox2.Text;
        }
        if(textBox1.Text.Length == 0 && textBox2.Text.Length == 0)
        {
            textBox3.Text = "0";
        }
    }

edit: treat textbox value as 0 when its empty.

This example will still error if you enter non-numeric values into the textbox.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM