1

我刚刚掌握了窍门Lightswitch,但是当我试图找出数据网格中的选定项目是否包含字母“CMP”时,我不断收到空引用异常错误。我环顾四周,但我认为我做错了什么。这是我的参考代码:

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)

但它总是给我同样的错误。任何帮助将非常感激!

4

1 回答 1

2

我猜测this.locationthis.location.selecteditem可能为空,所以你得到了那个错误。所以请尝试这个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;
        }
于 2014-04-28T06:02:21.360 回答