CareTaker22
CareTaker22

Reputation: 1300

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

Upvotes: 3

Views: 8450

Answers (3)

MakePeaceGreatAgain
MakePeaceGreatAgain

Reputation: 37000

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.

Upvotes: 6

AnjumSKhan
AnjumSKhan

Reputation: 9827

if( null != lblSupplierEmailAddress.Content 
    && string.IsNullOrEmpty(lblSupplierEmailAddress.Content.ToString() )

Upvotes: 0

Ian
Ian

Reputation: 30813

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
    }

Upvotes: 3

Related Questions