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 you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With