How to resolve "The input string was not in the 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 for:

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

After starting the page in the browser, I get System.FormatException: the input line was not in the correct format.

+3
source share
4 answers

The problem is with the line

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

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

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

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

Since it Label1.Textholds Label, which cannot be parsed into an integer, you need to convert the associated text of the text field to an integer

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

When using TextBox2.Textas a source for a numeric value, you must first check if the value exists, and then convert to an integer.

If the text box is empty when called Convert.ToInt32, you will receive System.FormatException. Suggest a try:

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

Replace

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

Source: https://habr.com/ru/post/1688176/


All Articles