10

我尝试了什么:

标记:

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

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

4

4 回答 4

13

问题在于线路

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

Label1.Text可能是也可能不是 int。检查

改为使用Int32.TryParse(value, out number)。这将解决你的问题。

int imageWidth;
if(Int32.TryParse(Label1.Text, out imageWidth))
{
    Image1.Width= imageWidth;
}
于 2012-09-04T18:30:35.550 回答
2

如果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.
   }
}
于 2012-09-04T18:30:54.653 回答
0

用。。。来代替

imageWidth = 1 * Convert.ToInt32(Label1.Text);
于 2012-09-04T18:32:09.087 回答
0

因为Label1.TextisholdLabel不能解析成整数,所以需要将关联文本框的文本转换成整数

imageWidth = 1 * Convert.ToInt32(TextBox2.Text);
于 2012-09-04T18:23:59.500 回答