Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating label content equal to null or string.Empty

Tags:

c#

label

wpf

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

like image 597
CareTaker22 Avatar asked Dec 20 '25 07:12

CareTaker22


2 Answers

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.

like image 186
MakePeaceGreatAgain Avatar answered Dec 21 '25 21:12

MakePeaceGreatAgain


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
    }
like image 35
Ian Avatar answered Dec 21 '25 21:12

Ian