我正在尝试检查标签的值是否等于null, " ", string.Empty
,但每次运行我的编码时,都会出现以下错误:
对象引用未设置为对象的实例。
这是我的编码:
if (lblSupplierEmailAddress.Content.ToString() == "") //Error here
{
MessageBox.Show("A Supplier was selected with no Email Address. Please update the Supplier's Email Address", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
如何检查标签内的字符串值是否等于null?我可能会遗漏一些简单的东西,如果是这样,请忽略我的无能:P
答案 0 :(得分:5)
更改
if (lblSupplierEmailAddress.Content.ToString() == "")
到
if (String.IsNullOrEmpty((string) lblSupplierEmailAddress.Content)
当lblSupplierEmailAddress.Content
实际为null
时,您当然不能在其上调用ToString
,因为它会导致NullReferenceException
。但是,静态IsNullOrEmpty
- 方法会对此表示尊重,如果true
为Content
则返回null
。
答案 1 :(得分:2)
在C#6.0中这样做
if(lblSupplierEmailAddress?.Content?.ToString() == "")
如果lblSupplierEmailAddress
始终存在,您可以执行以下操作:
if(lblSupplierEmailAddress.Content?.ToString() == "")
等效代码为:
if(lblSupplierEmailAddress.Content != null)
if (lblSupplierEmailAddress.Content.ToString() == ""){
//do something
}
答案 2 :(得分:0)
if( null != lblSupplierEmailAddress.Content
&& string.IsNullOrEmpty(lblSupplierEmailAddress.Content.ToString() )