C# int.Parse,输入字符串的格式不正确

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9372210/
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 07:04:38  来源:igfitidea点击:

int.Parse, Input string was not in a correct format

c#

提问by user575219

How would I parse an empty string? int.Parse(Textbox1.text)gives me an error:

我将如何解析空字符串?int.Parse(Textbox1.text)给我一个错误:

Input string was not in a correct format.
System.FormatException: Input string was not in a correct format.

输入字符串的格式不正确。
System.FormatException: 输入字符串的格式不正确。

If the text is empty (Textbox1.text = ''), it throws this error. I understand this error but not sure how to correct this.

如果文本为空 ( Textbox1.text = ''),则会引发此错误。我理解这个错误,但不知道如何纠正这个错误。

采纳答案by userx

If you're looking to default to 0 on an empty textbox (and throw an exception on poorly formatted input):

如果您希望在空文本框中默认为 0(并在格式错误的输入上引发异常):

int i = string.IsNullOrEmpty(Textbox1.Text) ? 0 : int.Parse(Textbox1.Text);

If you're looking to default to 0 with any poorly formatted input:

如果您希望将任何格式错误的输入默认为 0:

int i;
if (!int.TryParse(Textbox1.Text, out i)) i = 0;

回答by xandercoded

if(!String.IsNullOrEmpty(Textbox1.text))
    var number = int.Parse(Textbox1.text);

Or even better:

或者甚至更好:

int number;

int.TryParse(Textbox1.Text, out number);

回答by Ry-

Well, what do you wantthe result to be? If you just want to validate input, use int.TryParseinstead:

嗯,你希望结果是什么?如果您只想验证输入,请int.TryParse改用:

int result;

if (int.TryParse(Textbox1.Text, out result)) {
    // Valid input, do something with it.
} else {
    // Not a number, do something else with it.
}

回答by Victor Chekalin

Try this:

尝试这个:

int number;
if (int.TryParse(TextBox1.Text, out number))
{
    //Some action if input string is correct
}

回答by SolidSnake

you can wrap it with simple try/catch...

你可以用简单的try/catch...

回答by devinbost

You could also use an extension method like this:

您还可以使用这样的扩展方法:

public static int? ToNullableInt32(this string s)
{
    int i;
    if (Int32.TryParse(s, out i)) return i;
    return null;
}

Here's the reference: How to parse a string into a nullable int in C# (.NET 3.5)

这是参考:How to parse a string into a nullable int in C# (.NET 3.5)

回答by Deepu Reghunath

If the input is a number or an empty string this will work. It will return zero if the string is empty or else it will return the actual number.

如果输入是数字或空字符串,这将起作用。如果字符串为空,它将返回零,否则将返回实际数字。

int.Parse("0"+Textbox1.Text)