string-int-string generates exception with ConvertTo...

  • Thread starter Thread starter js
  • Start date Start date
J

js

Hello,

I have two text boxes accepting ints and displaying their Sum.

This code works:

string ans;
ans = Convert.ToString(Convert.ToInt32(textBoxX.Text) +
Convert.ToInt32(textBoxY.Text));
labelAnswer.Text = ans;



But this code generates InvalidCastException:

labelAnswer.Text = Convert.ToString( Convert.ToInt32(textBoxX.Text) +

Convert.ToInt32(textBoxY) );



Why? What's the difference?

brad.
 
Below.
Hello,

I have two text boxes accepting ints and displaying their Sum.

This code works:

string ans;
ans = Convert.ToString(Convert.ToInt32(textBoxX.Text) +
Convert.ToInt32(textBoxY.Text));
labelAnswer.Text = ans;



But this code generates InvalidCastException:

labelAnswer.Text = Convert.ToString( Convert.ToInt32(textBoxX.Text) +

Convert.ToInt32(textBoxY) );
Assuming this is your actual code, you're asking the Convert class to
convert textBoxY to an Int32. Specify the string, textBoxY.Text, and
you'll be fine.

Austin Ehlers
 
Back
Top