Pergunta

I'm just getting the hang of Lightswitch, but I keep getting the null reference exception error when I'm trying to find out if a selected item in a datagrid contains the letters "CMP". I look all over the place but I think I'm doing something wrong. Here is my code for reference:

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;
        }

I also tried

if(this.location.selecteditem.locationID != null)

if(string.IsNullOrEmpty)

but it always throws me the same error. Any help would be much appreciated!

Foi útil?

Solução

I guss this.location or this.location.selecteditem may be null, So you got that error. So please try this if condition instead of your if condition way

if(this.location != null && this.location.selecteditem !=null && this.location.selecteditem.locationID != null)
{
       //Write your code here 
}

So your final code look like

        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;
        }
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top