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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12269254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 22:42:04  来源:igfitidea点击:

How to resolve "Input string was not in a correct format." error?

c#asp.net

提问by Md. Arafat Al Mahmud

What I tried:

我试过的:

MarkUP:

标记:

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

Code Behind:

背后的代码:

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

After running the page on a browser, I get the System.FormatException: Input string was not in a correct format.

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

采纳答案by Deval Ringwala

Problem is with line

问题是线路

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

Label1.Textmay or may not be int. Check http://msdn.microsoft.com/en-us/library/sf1aw27b.aspxfor exceptions.

Label1.Text可能是也可能不是 int。检查http://msdn.microsoft.com/en-us/library/sf1aw27b.aspx是否有异常。

Use Int32.TryParse(value, out number)instead. That will solve your problem.

使用Int32.TryParse(value, out number)来代替。那将解决您的问题。

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

回答by Habib

Because Label1.Textis holding Labelwhich can't be parsed into integer, you need to convert the associated textbox's text to integer

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

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

回答by David W

If using TextBox2.Textas the source for a numeric value, it must first be checked to see if a value exists, and then converted to integer.

如果TextBox2.Text用作数字值的来源,则必须先检查它是否存在值,然后再转换为整数。

If the text box is blank when Convert.ToInt32is called, you will receive the System.FormatException. Suggest trying:

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

回答by Aghilas Yakoub

Replace with

用。。。来代替

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