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