-4
protected void Button1_Click(object sender, EventArgs e)
{
    string b = "hello";
    TextBox1.Text = Convert.ToInt32(b).ToString();
}

Error:

Input string was not in a correct format .How do I convert a string to an integer in C#?

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88
Reshmy
  • 1
  • 1

1 Answers1

3
 string b = "hello";
 Int32 outPut=0;
 Int32.TryParse(b,out outPut);//0
 TextBox1.Text = outPut.ToString();

Since b holds a string that cannot be converted to integer you will get 0 in TextBox1.

Int32.Parse() and Convert.Int32() are other possible methods of converting string to integer. but both these methods are not capable of handles null as well as they convert only if the input to the methord is convertible to integer, otherwise it throws format exception.

Where as Int32.TryParse() will not throws any exception on wrong input, it gives 0 in the case of wrong input. and return a Boolean value that indicates whether the conversion is successful or not.

sujith karivelil
  • 28,671
  • 6
  • 55
  • 88