c# – How to resolve Input string was not in a correct format. error?

c# – How to resolve Input string was not in a correct format. error?

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;
}

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.
   }
}

c# – How to resolve Input string was not in a correct format. error?

Because Label1.Text is holding Label which cant be parsed into integer, you need to convert the associated textboxs text to integer

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

Leave a Reply

Your email address will not be published.