1

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.'

  • 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 – Lucas Mar 13 '18 at 20:45
  • Yes. I imagined that is the problem. But I cannot think of a simple solution to this problem. Should I change the textBlock's assignment on the list reload to something temporary? – positive perspective Mar 13 '18 at 20:48
  • 1
    That, or you could wrap the logic after setting the 'selected' variable in a null check: if (selected != null) { SelectedProductName.Text = selected.ProductId.ToString(); } else { SelectedProductName.Text = "Default product name"; } – Lucas Mar 13 '18 at 20:50
  • @elhs16 That is very nice. It works obviously. Sometimes the simplest is the hardest to see. Thank you very much elhs16 – positive perspective Mar 13 '18 at 21:01

1 Answers1

1

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";
    }
}
Lucas
  • 431
  • 2
  • 10