Tuesday, January 12, 2016

Input string was not in a correct format in ASP.NET/C#

Server Error in '/' Application.
Input string was not in a correct format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: Input string was not in a correct format.

Source Error:

Line 31:         int ppi = Convert.ToInt32(Text1.Text);


I tried to change int ppi = Convert.ToInt32(Text1.Text); statement to int ppi = int.Parse(Text1.Text); and int ppi = Int32.Parse(Text1.Text); and int ppi = Int16.Parse(Text1.Text); but it didn't work.

The reason was I was using a float value and parsing into an integer one, so I change the erroneous statement to the following, and it worked:

float ppi =  float.Parse(Text1.Text);


You will get an error if you are trying to perform something like

float ppi =  float.Parse(float.Parse(Text1.Text)*100);

because of float. The parse function expects a string to convert into a float, and in the previous case, we are trying to convert a float to float, so that will throw an error.

Correct way is float ppi =  float.Parse(Text1.Text)*100;

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.