验证标签内容等于null或string.Empty

时间:2016-01-25 08:28:46

标签: c# wpf label

我正在尝试检查标签的值是否等于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

3 个答案:

答案 0 :(得分:5)

更改

if (lblSupplierEmailAddress.Content.ToString() == "")

if (String.IsNullOrEmpty((string) lblSupplierEmailAddress.Content)

lblSupplierEmailAddress.Content实际为null时,您当然不能在其上调用ToString,因为它会导致NullReferenceException。但是,静态IsNullOrEmpty - 方法会对此表示尊重,如果trueContent则返回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() )