1

I have a rather straightforward routine that will occasionally cause a null reference exception and I've been unable to identify a reason or solution to the problem.

The goal is a function which will clear then populate a listview and if a selected item criteria is specified (typically a string or internal object id) that item will be selected within the listview.

this.listView.Items.Clear();
foreach(var obj in objectList)
{
    var lvi = new ListViewItem(new[] {obj.Column1, obj.Column2}) { Tag = obj };
    this.listView.Items.Add(lvi);
    if (obj.Column1 == selectedData)
    {
        lvi.Selected = true; //Occasional null reference
    }
}

The stack trace at that point yields:

System.NullReferenceException: Object reference not set to an instance of an object.
    at System.Windows.Forms.ListViewItem.set_Selected(Boolean value)
    at <method of above code> @ <line number for "Selected = true">

Edit: I do not consider this a duplicate of the proposed question as none of my directly controlled objects are null. Something internal with the ListViewItem object is sometimes null and causes interacting with the property Selected to error.

Although I do not know what the internal logic of .Add is doing, I suspect it can create a new object and thus whatever its return value is should be used.

this.listView.Items.Clear();
foreach(var obj in objectList)
{
    var lvi = this.listView.Items.Add(new ListViewItem(new[] {obj.Column1, obj.Column2}) { Tag = obj });
    if (obj.Column1 == selectedData)
    {
        lvi.Selected = true;
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Tribmos
  • 49
  • 5
  • 4
    Is some other thread doing something with `listView.Items`? – CodeCaster Feb 02 '18 at 14:34
  • 1
    This sounds like a multi-threading issue. – Rafael Feb 02 '18 at 14:39
  • Did you ever solve this? I have the exact same problem. It was working fine yesterday, now I'm getting a NullReferenceException at `System.Windows.Forms.ListViewItem.set_Selected(Boolean value)`. – Robert Woods Feb 15 '18 at 11:15
  • 1
    Yup! I updated my question at the bottom with the solution I came to (using the result of the add function). Due to the question being tagged as 'duplicate' I cannot have a formal answer post. – Tribmos Feb 15 '18 at 20:37
  • How do you Remove the `Marked as Duplicate`. I had this same issue. This Question and it's few answers helped me figure out a solution. I wanted to post my solution however I am seeing that since it is marked as duplicate I am unable to provide another answer. While this post deals with Null Exception Error it comes with a twist. – Code Novice Oct 24 '18 at 23:08
  • Needs someone with higher credentials then us. They deem it as a duplicate and I've given up trying to argue. I'm glad to hear that my problem and solution were able to help. – Tribmos Oct 26 '18 at 19:57

0 Answers0