[英]Check if textbox is empty - is there a better way?
我想检查文本框是否为空。
有没有比以下更好(更优雅,更简单)的方法:
String.IsNullOrWhiteSpace(null == txtBox ? null : txtBox.Text)
值得注意的是,如果txtBox
为null
,则String.IsNullOrWhiteSpace(txtBox.Text)
会引发NullReferenceException
。
并非如此-但是,如果可以节省时间,您可以做一点扩展:
public static class TextBoxExtensions
{
public static bool IsEmpty(this TextBox textBox)
{
return string.IsNullOrWhiteSpace(null == textBox ? null : textBox.Text);
}
}
用法:
if(TextBox1.IsEmpty())
{
....
假设您的txtBox
可以为null(我想这是一个动态创建的控件),则可以执行以下操作:
bool isEmptyOrNull = txtBox == null || string.IsNullOrWhiteSpace(txtBox.Text)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.