简体   繁体   中英

Error with adding two textbox values into third one C#

I am trying to insert textbox1 + textbox2 = textbox3 . And all my textboxes are set to selectAll(); while entering into textbox. So when I entered to textbox1 all the text will be in select mode and if I click backspace all data will be removed and an error occurring like

Input string was not in correct format

My code is

textBox3.Text = (int.Parse(textBox1.Text) + int.Parse(textBox2.Text)).ToString();`

I tried like

       if (textBox1.Text != "")
        {
            textBox3.Text = (int.Parse(textBox1.Text) + int.Parse(textBox2.Text)).ToString();
        }

In this case The value in the Textbox three is not changing when I click backspace. Means textbox will be null. That's why value is not changing in thired textbox. Please help me. How could I ovecome this problem?

You are assuming that your inputs ( textBox1.Text and textBox2.Text ) are integers.

If they are not, int.Parse will fail and give you the error you are seeing.

You need to use int.TryParse :

int result1 = 0:
int.TryParse(textBox1.Text, out result1);
int result2 = 0:
int.TryParse(textBox2.Text, out result2);

textBox3.Text = (result1 + result2).ToString():

Int is not a nullable item - and since you are tyring to parse a null value (after your back space) it is casuing the error.

use instead int.TryParase(value_to_parse ,out where to store resulting Int) TryParse returns a boolean to state if parsing was sucessfull Regards

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