16

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.

Sandy
  • 6,285
  • 15
  • 65
  • 93
Md. Arafat Al Mahmud
  • 3,124
  • 5
  • 35
  • 66

4 Answers4

17

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;
}
Osama Rizwan
  • 615
  • 1
  • 7
  • 19
Deval Ringwala
  • 348
  • 1
  • 5
  • This error message could be thrown when try to Convert.ToDouble input comming from user with different cultureinfo, so you could use Convert.ToDouble (String, IFormatProvider) instead of just Convert.ToDouble (String). It is hard to debug, because program will work on you system, but will throw error on some of its users, this is why I have a method to log errors on my server and I found out for the problem fastly. – vinsa Apr 07 '18 at 14:24
3

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.
   }
}
bluish
  • 26,356
  • 27
  • 122
  • 180
David W
  • 10,062
  • 34
  • 60
0

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);
Habib
  • 219,104
  • 29
  • 407
  • 436
0

Replace with

imageWidth = 1 * Convert.ToInt32(Label1.Text);
Aghilas Yakoub
  • 28,516
  • 5
  • 46
  • 51