[英]int.Parse, Input string was not in a correct format
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.如果文本为空( Textbox1.text = ''
),则会引发此错误。 I understand this error but not sure how to correct this.我理解这个错误,但不知道如何纠正这个错误。
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;
Well, what do you want the result to be?嗯,你希望结果是什么? If you just want to validate input, use int.TryParse
instead:如果您只想验证输入,请改用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.
}
if(!String.IsNullOrEmpty(Textbox1.text))
var number = int.Parse(Textbox1.text);
Or even better:或者甚至更好:
int number;
int.TryParse(Textbox1.Text, out number);
Try this:尝试这个:
int number;
if (int.TryParse(TextBox1.Text, out number))
{
//Some action if input string is correct
}
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)
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)
你可以用简单的try/catch
包装它......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.