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