2012-09-04 90 views
3

我的尝试:如何解决“输入字符串格式不正确”。错误?

标记:

<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:输入字符串没有一个正确的格式。

+1

变化'Convert.ToInt32(Label1.Text)''来Convert.ToInt32(TextBox2.Text)' –

+0

@AndreCalil我只是尝试,仍然得到了同样的错误 –

+0

在'SliderExtender1'处,改变'Bound'和'Target'控制 –

回答

4

问题是与线

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

因为Label1.Text持有Label不能被解析成整数,则需要相关文本框的文本转换为整数

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

我只是试过,仍然有相同的错误 –

+1

把一个断点,看看里面TextBox2.Text是什么 – Habib

0

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

替换

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