C# 如何解决;输入字符串的格式不正确。”;错误?

C# 如何解决;输入字符串的格式不正确。”;错误?,c#,asp.net,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" TargetCon

我的尝试:

 <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>
protected void setImageWidth()
{
    int imageWidth;
    if (Label1.Text != null)
    {
        imageWidth = 1 * Convert.ToInt32(Label1.Text);
        Image1.Width = imageWidth;
    }
}
标记:

 <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>
protected void setImageWidth()
{
    int imageWidth;
    if (Label1.Text != null)
    {
        imageWidth = 1 * Convert.ToInt32(Label1.Text);
        Image1.Width = imageWidth;
    }
}

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

因为
Label1.Text
持有
Label
,无法解析为整数,所以需要将相关文本框的文本转换为整数

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

问题在于线路

imageWidth = 1 * Convert.ToInt32(Label1.Text);
Label1.Text
可以是int,也可以不是int

改用
Int32.TryParse(值,输出编号)
。那会解决你的问题

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

如果使用
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.
   }
}
取代

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

Convert.ToInt32(Label1.Text)
更改为
Convert.ToInt32(TextBox2.Text)
@和校准我刚刚尝试过,但仍然在
slidextender1
上遇到相同的错误,更改
绑定
目标
控件我应该怎么做?这不是C代码的问题吗?为什么你有一个标签和一个文本框?我刚刚尝试了,但仍然得到了相同的错误。请输入一个断点,然后查看TextBox2.text中的内容。当尝试转换时,可能会抛出此错误消息。来自具有不同文化信息的用户的ToDouble input提交,因此可以使用Convert.ToDouble(字符串, IFormatProvider),而不仅仅是Convert.ToDouble(字符串)。调试是很困难的,因为程序将在您的系统上运行,但会在某些用户身上抛出错误,这就是为什么我有一种方法在我的服务器上记录错误,我很快就发现了问题。