如何解决“输入字符串格式不正确。”错误?
我尝试了什么:
标记:
代码背后:
protected void setImageWidth() { int imageWidth; if (Label1.Text != null) { imageWidth = 1 * Convert.ToInt32(Label1.Text); Image1.Width = imageWidth; } }
在浏览器上运行页面后,我得到System.FormatException
:输入字符串的格式不正确。
问题在于线
imageWidth = 1 * Convert.ToInt32(Label1.Text);
Label1.Text
可能是也可能不是int。 有关例外情况,请访问http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx 。
请改用Int32.TryParse(value, out number)
。 这将解决您的问题。
int imageWidth; if(Int32.TryParse(Label1.Text, out imageWidth)) { Image1.Width= imageWidth; }
因为Label1.Text
持有无法解析为整数的Label
,所以需要将关联的文本框的文本转换为整数
imageWidth = 1 * Convert.ToInt32(TextBox2.Text);
用。。。来代替
imageWidth = 1 * Convert.ToInt32(Label1.Text);
如果使用TextBox2.Text
作为数值的源,则必须首先检查它是否存在值,然后转换为整数。
如果在调用Convert.ToInt32
时文本框为空,您将收到System.FormatException
。 建议尝试:
protected void SetImageWidth() { try{ Image1.Width = Convert.ToInt32(TextBox1.Text); } catch(System.FormatException) { Image1.Width = 100; // or other default value as appropriate in context. } }