【问题标题】:How to resolve "Input string was not in a correct format." error? [duplicate]如何解决“输入字符串格式不正确。”错误? [复制]
【发布时间】:2020-11-27 19:45: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:输入字符串格式不正确。

  • Convert.ToInt32(Label1.Text) 更改为Convert.ToInt32(TextBox2.Text)
  • @AndreCalil我刚刚尝试过,但仍然遇到同样的错误
  • SliderExtender1,更改BoundTarget 控件
  • 我为什么要 ?这不是 C# 代码的问题吗?
  • 为什么你有一个标签和一个文本框?

标签: c# asp.net


【解决方案1】:

问题在于线路

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

Label1.Text 可能是也可能不是 int。 Check

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

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

【讨论】:

  • 当尝试从具有不同文化信息的用户输入 Convert.ToDouble 时,可能会抛出此错误消息,因此您可以使用 Convert.ToDouble (String, IFormatProvider) 而不仅仅是 Convert.ToDouble (String)。很难调试,因为程序可以在你的系统上运行,但会在它的一些用户身上抛出错误,这就是为什么我有一种方法可以在我的服务器上记录错误并且我很快就发现了问题。
【解决方案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.
   }
}

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

    • 我刚刚尝试过,仍然遇到同样的错误
    • 放一个断点,看看 TextBox2.Text 里面有什么
    【解决方案4】:

    用。。。来代替

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多