如何解决"输入字符串格式不正确".错误?

Md.*_*mud 5 c# asp.net

我尝试了什么:

标记:

 <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>
Run Code Online (Sandbox Code Playgroud)

代码背后:

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

在浏览器上运行页面后,我得到System.FormatException:输入字符串的格式不正确.

小智 9

问题在于线

imageWidth = 1 * Convert.ToInt32(Label1.Text);
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)