By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,516 Members | 1,107 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,516 IT Pros & Developers. It's quick & easy.

ListViewItem.Index = -1 ... why?

P: n/a
Hi everyone

I have a form which contains a ListView control. The code
handles the SelectedIndexChanged event, and changes some
icons on some items in the ListView.

I've found that when I deactivate and reactivate the form
(an MDI child, in case that matters), the
SelectedIndexChanged event is fired. On its own, that's not
a problem... but the following code causes trouble:
Dim lvw As ListView = Me.MyListView

' get the currently selected item
Dim itm1 As ListViewItem = lvw.SelectedItems(0)

If (itm1.Index < lvw.Items.Count - 1) Then
' get the following item in the list
Dim itm2 As ListViewItem = lvw.Items(itm1.Index + 1)

' and change its icon
itm2.ImageIndex = 0
End If
The line that sets the ImageIndex is causing an exception,
saying that "index" cannot be -1. But -1 is a valid value
for ImageIndex, and I passed a value of zero. So it can't
be talking about the value I specified for ImageIndex...

The call stack shows:

System.Windows.Forms.ListView.SetItemImage(int index=-1,
int image=0)
System.Windows.Forms.ListViewItem.set_Image(int value=0)

So "set_Image" is passing a value of -1 ... and sure
enough, if I put a breakpoint on the line of code that sets
"itm2.ImageIndex", I can see that "itm2.Index" is indeed -1.

Why?

i.e., I just looked it up by its index, so obviously the
ListView knows this item's index... so why does the item
not know its own index?

Can anyone suggest a workaround, other than simply ignoring
the exception? I'd rather not do that because then it might
be possible that the icons do not get set properly.

Thanks

-- graham

Nov 21 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.