How to resolve "Input string was not in a correct format." error? [duplicate]

What I tried:

MarkUP:

 <asp:TextBox runat="server"></asp:TextBox> <asp:Label runat="server" AssociatedControlID="TextBox2" Text="Label"></asp:Label> <asp:SliderExtender 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.

7

4 Answers

The problem is with line

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

Label1.Text may or may not be int. Check.

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

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

If using TextBox2.Text as the source for a numeric value, it must first be checked to see if a value exists, and then converted to integer.

If the text box is blank when Convert.ToInt32 is called, you will receive the System.FormatException. Suggest trying:

protected void SetImageWidth() { try{ Image1.Width = Convert.ToInt32(TextBox1.Text); } catch(System.FormatException) { Image1.Width = 100; // or other default value as appropriate in context. } } 

Because Label1.Text is holding Label which can't be parsed into integer, you need to convert the associated textbox's text to integer

imageWidth = 1 * Convert.ToInt32(TextBox2.Text); 
2

Replace with

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

You Might Also Like