Converting string to int is simple in c#. There are two comman ways
to convert string to int.
- Convert.ToInt32
- Int32.TryParse
Here is the screen shot of our string to int converter sample application:Note that our integer number must be between −2,147,483,648 and +2,147,483,647 range.
The c# source code to convert string to integer
private void btnConvert_Click(object sender, EventArgs e) { int numValue = 0; string strValue = string.Empty; strValue = tbInput.Text.Trim(); try { numValue = Convert.ToInt32(strValue); lblResult.Text = numValue.ToString(); } catch (Exception exc) { tbInput.Text = string.Empty; lblResult.Text = string.Empty; MessageBox.Show("Error occured:" + exc.Message); } } private void btnTryParse_Click(object sender, EventArgs e) { ConvertToIntTryParse(); } private void ConvertToIntTryParse() { int numValue = 0; bool result = Int32.TryParse(tbInput.Text, out numValue); if (true == result) lblResult.Text = numValue.ToString(); else MessageBox.Show("Cannot parse string as int number"); }
No comments:
Post a Comment