简体   繁体   中英

Validating label content equal to null or string.Empty

I'm trying to check if the value of a label is equal to null, " ", string.Empty , but every time I run through my coding, I get the following error:

Object reference not set to an instance of an object.

Here is my coding:

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;
}

How can I check if the string value inside my label is equal to null? I might be missing something simple, if so please ignore my incompetence :P

Change

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

To

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

When lblSupplierEmailAddress.Content is actually null you can of course not call ToString on it as it will cause a NullReferenceException . However the static IsNullOrEmpty -method takes respect on this and returns true if Content is null .

In C#6.0 This will do

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

Else if the lblSupplierEmailAddress always exists, you could simply do:

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

The equivalent code would be:

if(lblSupplierEmailAddress.Content != null)
    if (lblSupplierEmailAddress.Content.ToString() == ""){
        //do something
    }
if( null != lblSupplierEmailAddress.Content 
    && string.IsNullOrEmpty(lblSupplierEmailAddress.Content.ToString() )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM