我的问题是关于c# [英] my question is about c#

查看:63
本文介绍了我的问题是关于c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

int rows = Convert.ToInt32(txtrows.Text.ToString());

txtrows是文本框的id ..

当文本框为空时,错误累积(你的输入字符串格式不正确)..如果文本不为空则则不显示任何错误..

任何解决方案??

int rows = Convert.ToInt32(txtrows.Text.ToString());
txtrows is the id of a text box..
when the textbox is empty,the an error accour (your input string is not in correct format ) .. if the text is not empty then is does not show any error..
any solution ??

推荐答案

为什么不使用'TryParse运算符的全部功能:
Why not use the full power of the 'TryParse operator:
// this code requires:
using System.Globalization;
//
// note: prior to .NET 4 an invalid culture specification string would
// throw an 'ArgumentException. in .NET 4 the exception thrown is
// a 'CultureNotFoundException
CultureInfo cultureProvider = new CultureInfo("en-US");

int rows;

if (Int32.TryParse(txtrows.Text, NumberStyles.Integer, cultureProvider , out rows))
{
    // valid integer now in 'rows
}
else
{
    // handle no content, or invalid content, in the TextBox
    throw new ArgumentException("Invalid entry in 'txtrow");
}


怎么回事?您是否期望,如果您的字符串为空,将返回42?或者其他一些数字?



而不是转换使用 int.Parse (也可能抛出异常),或者 int.TryParse (将返回布尔值以表示成功)。至少这些方法的名称是足够的,并告诉我们到底发生了什么。请参阅:

http ://msdn.microsoft.com/en-us/library/system.int32.parse%28v=vs.110%29.aspx [ ^ ],

< a href =http://msdn.microsoft.com/en-us/library/system.int32.tryparse%28v=vs.110%29.aspx> http://msdn.microsoft.com/en-us /library/system.int32.tryparse%28v=vs.110%29.aspx [ ^ ]。



请了解所有6方法呢。 :-)



-SA
How else? Did you expect that, if your string is empty, 42 would be returned? Or some other number?

Instead of Convert use either int.Parse (may throw exception as well), or int.TryParse (will return Boolean to indicate success). At least the names of these methods are adequate and tell us what really happens. Please see:
http://msdn.microsoft.com/en-us/library/system.int32.parse%28v=vs.110%29.aspx[^],
http://msdn.microsoft.com/en-us/library/system.int32.tryparse%28v=vs.110%29.aspx[^].

Please learn what all 6 methods do. :-)

—SA


你应该使用TryParse [ ^ ]此方法将字符串转换为 0 表示可能的异常,在你的情况下是空字符串。
You should use TryParse [^] and this method will convert the string to 0 for possible exceptions, and in your case for empty string.


这篇关于我的问题是关于c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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