Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

asp.net

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.

like image 898
Md. Arafat Al Mahmud Avatar asked Sep 04 '12 18:09

Md. Arafat Al Mahmud


People also ask

What do you mean by input string?

String input templates allow you to specify the type, order, and number of characters a user can enter in a data entry field. You can define string input templates only on single‑line character data entry fields.

What is a format exception?

A FormatException exception can be thrown for one of the following reasons: In a call to a method that converts a string to some other data type, the string doesn't conform to the required pattern. This typically occurs when calling some methods of the Convert class and the Parse and ParseExact methods of some types.


1 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;
}
like image 145
Deval Ringwala Avatar answered Oct 21 '22 18:10

Deval Ringwala