int.Parse,输入字符串的不正确的格式 [英] int.Parse, Input string was not in a correct format
问题描述
我将如何解析一个空字符串? int.Parse(Textbox1.text)
给我一个错误:
How would I parse an empty string? int.Parse(Textbox1.text)
gives me an error:
输入字符串的不正确的格式。结果
System.FormatException:输入字符串的不正确的格式
Input string was not in a correct format.
System.FormatException: Input string was not in a correct format.
如果该文本是空的( Textbox1.text =''
),它抛出这个错误。我理解这个错误,但不知道如何纠正这一点。
If the text is empty (Textbox1.text = ''
), it throws this error. I understand this error but not sure how to correct this.
推荐答案
如果你正在寻找默认为0的空白文本框(并抛出一个异常的格式不正确输入):
If you're looking to default to 0 on an empty textbox (and throw an exception on poorly formatted input):
int i = string.IsNullOrEmpty(Textbox1.Text) ? 0 : int.Parse(Textbox1.Text);
如果你正在寻找默认为0任何格式混乱输入:
If you're looking to default to 0 with any poorly formatted input:
int i;
if (!int.TryParse(Textbox1.Text, out i)) i = 0;
这篇关于int.Parse,输入字符串的不正确的格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!