[英]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: 我正在尝试检查标签的值是否等于
null, " ", string.Empty
,但每次我运行我的编码时,都会收到以下错误:
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? 如何检查标签内的字符串值是否等于null? I might be missing something simple, if so please ignore my incompetence :P
我可能会遗漏一些简单的东西,如果是这样,请忽略我的无能: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
. 当
lblSupplierEmailAddress.Content
实际为null
您当然不能在其上调用ToString
,因为它会导致NullReferenceException
。 However the static IsNullOrEmpty
-method takes respect on this and returns true
if Content
is null
. 但是,静态
IsNullOrEmpty
-method对此采取尊重,如果Content
为null
,则返回true
。
In C#6.0 This will do 在C#6.0中这样做
if(lblSupplierEmailAddress?.Content?.ToString() == "")
Else if the lblSupplierEmailAddress
always exists, you could simply do: 否则,如果
lblSupplierEmailAddress
始终存在,您可以简单地执行:
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() )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.