Search code examples
c#listviewuwpselecteditemselecteditemchanged

ListView reloading error if one of the records is selected priorly


I have a ListView that pulls data from a database via class.

I also use listView_SelectionChanged to track the name of selected product.

 public void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        var selected = LstView.SelectedItem as Product;

            string prodName = selected.ProductId.ToString();
            SelectedProductName.Text = prodName;



    }

As you can see, when row of the ListView is selected, I pull the ProductId, store it in string prodName and then assign it to TextBlock SelectedProductName. At this point, when I hit Go! button to RELOAD same list, I get error on line:

 string prodName = selected.ProductId.ToString();

That says: System.NullReferenceException: 'Object reference not set to an instance of an object.'


Solution

  • Answer is in the comments, this is posted for future devs who stumble upon this question.

    The Problem: When you reload the list, the selected item changes to null as nothing is selected anymore. This is causing your variable 'selected' to be null, and you cannot access properties/methods of null classes. Think of it this way. You buy a car (your list), you install a new touch screen radio (you selected an item), you sell the car and buy a new one (you clicked the button that reloads the list), then you are trying to change the station on the radio of your old car

    The Solution:

    public void listView_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        var selected = LstView.SelectedItem as Product;
    
        if (selected != null)
        {
            SelectedProductName.Text = selected.ProductId.ToString();
        }
        else
        {
            SelectedProductName.Text = "Default Product Name";
        }
    }