Invalid index on second run through

pachjo

Well-known member
Joined
Dec 12, 2006
Messages
370
Programming Experience
10+
Hi

This code successfully outputs the column data of the selected row I click on in my listview

However when I click on another row I get an errror saying 0 is an invalid index?

It works perfect on every row as long as I click on that row first, after that I get the error

VB.NET:
Expand Collapse Copy
[SIZE=2][/SIZE][SIZE=2][COLOR=#0000ff]Dim[/COLOR][/SIZE][SIZE=2] SelItems [/SIZE][SIZE=2][COLOR=#0000ff]As[/COLOR][/SIZE][SIZE=2] ListView.SelectedListViewItemCollection = [/SIZE][SIZE=2][COLOR=#0000ff]Me[/COLOR][/SIZE][SIZE=2].lstTransactions.SelectedItems
MessageBox.Show(SelItems(0).SubItems(0).Text & [/SIZE][SIZE=2][COLOR=#800000]" "[/COLOR][/SIZE][SIZE=2] & _
SelItems(0).SubItems(1).Text & [/SIZE][SIZE=2][COLOR=#800000]" "[/COLOR][/SIZE][SIZE=2] & _
SelItems(0).SubItems(2).Text & [/SIZE][SIZE=2][COLOR=#800000]" "[/COLOR][/SIZE][SIZE=2] & _
SelItems(0).SubItems(3).Text & [/SIZE][SIZE=2][COLOR=#800000]" "[/COLOR][/SIZE][SIZE=2] & _
SelItems(0).SubItems(4).Text)
[/SIZE]

Any ideas?

Thanks
 
Not sure why but this seems to solve the problem?

VB.NET:
Expand Collapse Copy
If Me.lstTransactions.SelectedItems.Count > 0 Then

            MessageBox.Show(objSelectedItems(0).SubItems(0).Text & " " & _
                        objSelectedItems(0).SubItems(1).Text & " " & _
                        objSelectedItems(0).SubItems(2).Text & " " & _
                        objSelectedItems(0).SubItems(3).Text & " " & _
                        objSelectedItems(0).SubItems(4).Text)
End If

I would appreciate if anyone could explain why I need to place it in a IF/End If block in order to get it to work.

Also I would like to know how do I cycle through multiple selections as this only works on a single selcetion.

I have tried to do a for each but get many errors as I am not sure how I code the correct construct?
 
ListView control raises the SelectedIndexChanged event twice when selection changes, once for the item that was unselected and once for the new item selected.

SelectedItems is a collection of ListViewItem you can iterate with For-Each or For-Next loops. (or access by index like you do with first item 0)
 
ListView control raises the SelectedIndexChanged event twice when selection changes, once for the item that was unselected and once for the new item selected.

Aha that explains it perfectly, muchly appreciated, thanks;)

The for next works a trest too;)

Cheers
 
Back
Top