Search code examples
databasevb.netlistviewselectedindex

Retriving data from ListView control


I have a ListView control set up in details mode with 5 columns. It is populated by code using the following subroutine:

            For j = 0 To 14
                cmd = New OleDbCommand("SELECT TeacherName, ClassSubject, BookingDate, BookingPeriod FROM " & SchemaTable.Rows(i)!TABLE_NAME.ToString() & " WHERE (((BookingDate)=" & Chr(34) & Date.Today.AddDays(j) & Chr(34) & ") AND ((UserName)=" & Chr(34) & user & Chr(34) & "));", cn)
                dr = cmd.ExecuteReader
                Dim itm As ListViewItem
                Dim itms(4) As String
                While dr.Read()
                    itms(0) = dr(0)
                    itms(1) = SchemaTable.Rows(i)!TABLE_NAME.ToString()
                    itms(2) = dr(1)
                    itms(3) = dr(2)
                    itms(4) = dr(3)
                    itm = New ListViewItem(itms)
                    Manage.ManageList.Items.Add(itm)
                End While
            Next

Note that this is not the full routine, just the bit that populated the grid.

Now I need to retrieve data from the ListView control in order to delete a booking in my database. I used the following code to retrieve the content of each column:

ManageList.SelectedItems(0).Text

But it only seems to work on index 0. If I do:

ManageList.SelectedItems(3).Text

I get this error:

InvalidArgument=Value of '3' is not valid for 'index'. Parameter name: index

I'm pretty much stumped, it seems logical to me that index 1 will point to the 2nd column, index 2 to the 3rd etc, as it's 0 based?

Any help would be appreciated, thanks.


Solution

  • When you say ManageList.SelectedItems(3).Text, you're asking it for the forth item selected in your list, not the forth column of the item selected.

    See MSDN

    EDIT: Think of it this way: ManageList.SelectedItems(0)=itms, which is a string array. The following example shows how you can access the forth array value of the selected array in the list:

    Dim itms() As String = ManageList.SelectedItems(0)
    If itms.Length>3 Then
        itms(3).DoWhatever
    End If