Noobster Noobster - 23 days ago 8
C# Question

C# WinForms - Adding two textbox automatically

I'm building this three textbox where if the two textbox are filled the sum will be displayed however, when I input 10 + 10. The result is 1010. Can anbody help me with this?

Here's my code:

public void textBoxTranspo_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBoxTranspo.Text) && !string.IsNullOrEmpty(textBoxDaily.Text))
textBoxTotalAmount.Text = (Convert.ToInt32(textBoxTranspo.Text) + Convert.ToInt32(textBoxDaily.Text).ToString());
}

public void textBoxDaily_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(textBoxTranspo.Text) && !string.IsNullOrEmpty(textBoxDaily.Text))
textBoxTotalAmount.Text = (Convert.ToInt32(textBoxTranspo.Text) + Convert.ToInt32(textBoxDaily.Text).ToString());
}

Answer

It is the magic(polymorphism) of the + operator. it will add the values of two operands if the operands are of numeric types(int,long, double) and it will concatenate two operands if they are of type strings or even one string and second integer(as like in your case). Here in your case the .ToString() after convert creates the issues. You will get the expected result by removing that from that line.

An additional note : Convert.ToInt32 will throw FormatException if the input text is not convertible, so use have to use int.TryParse for converting text to integer. so the code will looks like this:

int intTranspo=0,intBoxDaily=0;

if(int.TryParse(textBoxTranspo.Text,out intTranspo) && int.TryParse(textBoxDaily.Text,out intBoxDaily))
   textBoxTotalAmount.Text = (intTranspo + intBoxDaily).ToString();