Wednesday, 28 December 2011

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:

Post a Comment