Md. Arafat Al Mahmud Md. Arafat Al Mahmud - 1 month ago 5
ASP.NET (C#) Question

how to resolve "Input string was not in a correct format." error?

what I tried:

MarkUP:

<asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

<asp:Label ID="Label1" runat="server" AssociatedControlID="TextBox2" Text="Label"></asp:Label>

<asp:SliderExtender ID="SliderExtender1" TargetControlID="TextBox2" BoundControlID="Label1" Maximum="200" Minimum="100" runat="server">
</asp:SliderExtender>


Code Behind:

protected void setImageWidth()
{
int imageWidth;
if (Label1.Text != null)
{
imageWidth = 1 * Convert.ToInt32(Label1.Text);
Image1.Width = imageWidth;
}
}


after running the page on a browser, i get the
System.FormatException
: Input string was not in a correct format.

Answer

Problem is with line

imageWidth = 1 * Convert.ToInt32(Label1.Text);

Label1.Text may or may not be int. Check http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx for exceptions.

use Int32.TryParse(value, out number); instead. That will solve your problem.

int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
    Image1.Width= imageWidth;
}