Jay
Jay

Reputation: 147

C# simple computation

Hi i'm making an simple c# computation sample Label1.Text = textBox1.Text + textbox2.Text i'm having a problem when i try to input 88.5 or 80.3 and compute my program is keep crashing a getting errors.i already convert the text to Int and here's my code:

 int i;
 i = Convert.ToInt32(textBox1.Text) + Convert.ToInt32(textBox2.Text);
 Label1.Text= i.ToString();

But it's working if i insert 88 and 80 . i know i miss something on this.anyone can help me? thank you

Upvotes: 0

Views: 1283

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500065

You're trying to convert "88.5" into an integer. It's not an integer, is it?

I suggest you use decimal instead - and use TryParse so that you can handle invalid user input without resorting to exceptions.

decimal input1, input2;
if (decimal.TryParse(textBox1.Text, out input1) &&
    decimal.TryParse(textBox1.Text, out input2))
{
    Label1.Text = (input1 + input2).ToString();
}
else
{
    Label1.Text = "Invalid input";
}

Upvotes: 5

Related Questions