BP Forums
NullReferenceException when adding item to generic list - Printable Version

+- BP Forums (https://bpforums.info)
+-- Forum: Archived Forums (https://bpforums.info/forumdisplay.php?fid=55)
+--- Forum: Archived Forums (https://bpforums.info/forumdisplay.php?fid=56)
+---- Forum: VB.NET (Visual Basic 2010/2008) (https://bpforums.info/forumdisplay.php?fid=8)
+----- Forum: Programming Help (https://bpforums.info/forumdisplay.php?fid=9)
+----- Thread: NullReferenceException when adding item to generic list (/showthread.php?tid=831)



NullReferenceException when adding item to generic list - brco900033 - 04-17-2014

I have a little problem that I can't seem to solve.
When I try to add a value (integer) to a generic list (of integer), I always get a NullReferenceException.

This is my code:
[code2=vbnet]Dim listIndexes As List(Of Integer) = Nothing
For Each i As ListViewItem In Me.listKeys.Items
For Each i2 As ListViewItem In Me.listKeys.Items
If i.Text = i2.Text Then
listIndexes.Add(i.Index) 'The error persists here: NullReferenceException
listIndexes.Add(i2.Index) 'and propably an error here too
End If
Next
Next
Me.SelectKeys(listIndexes) 'This line just selects the items in the listview[/code2]

I've discovered that the index of these two items in the listview are both zero.

Hope someone can help,
brco


Re: NullReferenceException when adding item to generic list - brandonio21 - 06-17-2014

Your problem lies within this line:

[code2=vbnet]Dim listIndexes As List(Of Integer) = Nothing[/code2]

So when you try to add items to the listIndexes variable, you are actually trying to add items to Nothing, hence your error. Thus, you need to initialize the list before putting anything into it. Try changing it to something like:

[code2=vbnet]Dim listIndexes As List(Of Integer) = New List(Of Integer)[/code2]