Saturday, April 11, 2009

Input String was not in correct format; String to Int32 Conversion Problem.

There is a strange behavior of the Convert Class, when converting a string of value 0 as decimal "0.0" using the code..




   1:  private void button1_Click(object sender, EventArgs e)

   2:          {

   3:              int Result = 0;

   4:              try

   5:              {

   6:                  string inputString = textBox1.Text;

   7:                  Result = Int32.Parse(inputString);

   8:                  label3.Text = Result.ToString();

   9:              }

  10:              catch (Exception Ex)

  11:              {

  12:                  MessageBox.Show(Ex.Message);

  13:              }

  14:          }



Where the textbox value is "0.0". It returns the Exception "Input string was not in correct format". For all other values it returns the equivalent Integer value including '0'.

How to Solve this problem?

Use the below code..




   1:   private void button1_Click(object sender, EventArgs e)

   2:          {

   3:              int Result = 0;

   4:              try

   5:              {

   6:                  string inputString = textBox1.Text;

   7:                  Result = Int32.Parse(inputString,NumberStyles.AllowDecimalPoint);

   8:                  label3.Text = Result.ToString();

   9:              }

  10:              catch (Exception Ex)

  11:              {

  12:                  MessageBox.Show(Ex.Message);

  13:              }

  14:          }



here NumberStyles is as Enumerator available in System.Globalization namespace.



Caution: Pass only strings with decimal points as argument



Enjoy!

2 comments:

  1. Hope you guys got a quick simple way to get around the exception..

    Have a nice day!

    ReplyDelete
  2. good one, continue giving tips like this

    ReplyDelete

Please leave your comments here to improve myself!