我正在尝试检查标签的值是否等于 null, "", string.Empty
,但每次我运行我的代码时,我都会收到以下错误:
Object reference not set to an instance of an object.
这是我的代码:
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;
}
如何检查标签内的字符串值是否为空?我可能遗漏了一些简单的东西,如果是这样请忽略我的无能:P
最佳答案
改变
if (lblSupplierEmailAddress.Content.ToString() == "")
到
if (String.IsNullOrEmpty((string) lblSupplierEmailAddress.Content)
当 lblSupplierEmailAddress.Content
实际上是 null
时,您当然不能对其调用 ToString
,因为它会导致 NullReferenceException
。然而,静态 IsNullOrEmpty
方法对此表示尊重,并在 Content
为 null
时返回 true
。
关于c# - 验证标签内容等于 null 或 string.Empty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34988044/