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#?
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#?
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 gives0
in the case of wrong input. and return aBoolean
value that indicates whether the conversion is successful or not.