Click here to Skip to main content
15,877,966 members
Please Sign up or sign in to vote.
4.67/5 (2 votes)
See more: (untagged)
Cheers to all the mavens out there on codeproject!

I've banged my head over this one for some time, and I don't understand the reason for this FormatException (log entry) as thrown by Convert.ToInt32 that uses an input value from an ASP .NET 2.0 form *with* validation:

<br />ERROR 16 Jul 2009 09:01:13,970 (Webpage code-behind class name) - Failed conversion of value<br />System.FormatException: Input string was not in a correct format.<br />   at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal)<br />   at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info)<br />   at (name of calling function in ASP.NET code-behind)<br />


The code-behind of the web page is as follows:

<br />try<br />{<br />    dataObject.Weight = Convert.ToInt32(txbWeight.Text);<br />}<br />catch (Exception e)<br />{<br />    log.Error("Failed conversion of value", e);<br />}<br />


And the web page has the following validation for the txbWeight TextBox control:

<br /><asp:CompareValidator runat="server" ControlToValidate="txbWeight" Type="Integer" <br />Operator="GreaterThanEqual" ValueToCompare="0" Text="Positive number only for weight."<br />Display="Dynamic" /><br />


I don't understand why this exception is thrown, because the validator ensures that an integer is being received from the user (txbWeight also has a RequiredFieldValidator). The odd thing is that dataObject receives the value despite the exception being thrown!? I don't believe I need to call Trim(), and trying this in the past did not fix the issue.

Any ideas?
Posted

Always use int.tryparse, not convert.toint32. Do you have text in there, do you need to tell the validator to accept an empty field ?

 
Share this answer
 
Turns out that for a certain navigation path (i.e. a redirection) in my web application, I was disabling the validation controls and the fields could have empty values resulting in this exception). I have since rewritten this bad code and indeed have changed over to the much better TryParse(...) method as Christian suggested.
 
Share this answer
 


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900