Friday, November 23, 2007

Error: Input string was not in a correct format.

How to avoid Error "Input string was not in a correct format"

To avoid error always make check whether you are passing a valid value to function.

Example:

Code Contain Error
protected void Page_Load(object sender, EventArgs e)
{
string str1 = "3.5";
string str2 = "";

//Here we know that str2 is blank, but when values are assigned dynamic it is
//Best practise to make check before passing value to function.
TestFn(float.Parse(str1),float.Parse(str2));
}

private void TestFn(float value1, float value2)
{
//Do Something...
}


Code with Check to Avoid Error
protected void Page_Load(object sender, EventArgs e)
{
string str1 = "3.5";
string str2 = "";

float fStr1;
if (str1 != string.Empty)
fStr1 = float.Parse(str1);
else
fStr1 = 0;

float fStr2;
if (str2 != string.Empty)
fStr2 = float.Parse(str2);
else
fStr2 = 0;

//Values are parse and check for validity before passing to function
TestFn(fStr1,fStr2);
}

private void TestFn(float value1, float value2)
{
//Do Something...
}

Note: Code is just for example and has practically of no meaning.

No comments:

Most Recent Post

Community Updates

Subscribe Blog via Email

Enter your email address:



Disclaimers:We have tried hard to provide accurate information, as a user, you agree that you bear sole responsibility for your own decisions to use any programs, documents, source code, tips, articles or any other information provided on this Blog.
Page copy protected against web site content infringement by Copyscape