I have a listview which has 7 columns. I want to add information on each column, but when it reaches the subitem 2 from the listView I get a System.ArgumentOutOfRangeException
even though I have that subitem.
Any idea why I get this error? I've tried to search for it but I haven't found a similar case. This is the part of the code where I get that error:
if (seen == true)
listView1.SelectedItems[0].SubItems[2].Tag = "Seen";
else
listView1.SelectedItems[0].SubItems[2].Tag = "Not Seen";
You probably do not have all those SubItems in each item.
Or maybe nothing is selected? (Note that the SelectionChanged
event gets called when an Item
is unselected as well!)
Note that every Item
in a ListView
can have its own number of SubItems, no matter how many Columns
you have created. These only provide a space to display the data, not slots you can access without creating SubItems
!
Therefore we must test it before we access it! In other words: The ListView
structure is not a 2d array but a jagged array!
This could be a possible check..:
if ( listView1.SelectedItems[0].Count > 0 &&
listView1.SelectedItems[0].SubItems.Count > 2 )
listView1.SelectedItems[0].SubItems[2].Tag = seen ? "Seen" : "Not Seen";
..but you know your code better and may well find a nicer way of doing the necessary tests..
Just do not rely on the number of SubItems
being equal to the number of Columns
. They are not related at all and either may be greater in each Item
!