int.Parse,输入字符串的不正确的格式 [英] int.Parse, Input string was not in a correct format

查看:1747
本文介绍了int.Parse,输入字符串的不正确的格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将如何解析一个空字符串? 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆