[英]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.