我只是抓住了Lightswitch
,但是当我试图找出数据网格中的所选项目是否包含字母时,我一直收到空引用异常错误&# 34; CMP&#34 ;.我到处都看,但我觉得我做错了什么。这是我的参考代码:
if(string.IsNullOrWhiteSpace(this.location.SelectedItem.locationID))
{
this.ShowMessageBox("test"); //not sure what to put there so I just made something up
}
else if (this.location.SelectedItem.locationID.Contains("CMP"))
{
this.FindControl("datePurchased").IsVisible = true;
this.FindControl("age").IsVisible = true;
this.FindControl("userList").IsVisible = true;
}
else
{
this.FindControl("datePurchased").IsVisible = false;
this.FindControl("age").IsVisible = false;
this.FindControl("userList").IsVisible = false;
}
我也试过
if(this.location.selecteditem.locationID != null)
if(string.IsNullOrEmpty)
但它总是抛出同样的错误。任何帮助将非常感激!
答案 0 :(得分:2)
我guss this.location
或this.location.selecteditem
可能为null,所以你得到了那个错误。
因此,请尝试使用此if
条件,而不是if
条件
if(this.location != null && this.location.selecteditem !=null && this.location.selecteditem.locationID != null)
{
//Write your code here
}
所以你的最终代码看起来像
if(this.location == null && this.location.selecteditem ==null && this.location.selecteditem.locationID == null)
{
this.ShowMessageBox("test"); //not sure what to put there so I just made something up
}
else if (this.location.SelectedItem.locationID.Contains("CMP"))
{
this.FindControl("datePurchased").IsVisible = true;
this.FindControl("age").IsVisible = true;
this.FindControl("userList").IsVisible = true;
}
else
{
this.FindControl("datePurchased").IsVisible = false;
this.FindControl("age").IsVisible = false;
this.FindControl("userList").IsVisible = false;
}