0

How do you get the item's index location in a list box and return the position number instead of a string? I tried returning the index position, but my code only returns the string instead of the position number, here is my code

If lstRoomsOccupied.SelectedIndex <> -1 Then
    strLocation = lstRoomsOccupied.Items(lstRoomsOccupied.SelectedIndex).ToString()
    strInput = InputBox("Enter the Number of Rooms Occupied on Floor " & strLocation.ToString())
Else
    MessageBox.Show("Select an item")

Can anyone help me how to return index position number?

4

2 回答 2

1

因为,索引是从零开始的,所以你需要+1SelectedIndex像这样:

If lstRoomsOccupied.SelectedIndex <> -1 Then
    strLocation = (lstRoomsOccupied.SelectedIndex + 1).ToString()
    strInput = InputBox("Enter the Number of Rooms Occupied on Floor " & strLocation)
Else
    MessageBox.Show("Select an item")
End If

注意:您不需要从.Items集合中获取项目的索引,因为您关心的只是索引。您获得了该项目的价值,因为您要求选择的项目。此外,您不需要.ToString()字符串,因为它已经是字符串。

于 2013-11-01T17:24:13.373 回答
1

我建议将您更改Listbox为 a ListView,并设置以下内容:

  Me.ListView1.View = View.List
  Me.ListView1.MultiSelect = False

然后创建以下内容Class

  Public Class Rooms
     Public Floor As Integer
     Public Number As Integer
  End Class

现在,要将项目添加到您的,ListView您可以执行以下操作:

    ' First create a 'Room' variable to store the Room's details
    Dim Room As New Rooms

    ' Set the floor number that the Room is on
    Room.Floor = 2

    ' Set the Room number
    Room.Number = 15

    ' Create a ListViewItem which will be added to the ListView
    Dim LVI As New ListViewItem
    LVI.Text = "Floor 2 Occupied Room 15"

    ' Now add the Room to the ListViewItem
    LVI.Tag = Room

    ' Add the ListViewItem to the ListView
    Me.ListView1.Items.Add(LVI)

当用户做出选择时,您可以像这样检索信息:

  Private Sub ListView1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles ListView1.SelectedIndexChanged

    If Me.ListView1.SelectedItems.Count > 0 Then
        ' Get the Room's details
        Dim Room As Rooms = CType(Me.ListView1.SelectedItems(0).Tag, Rooms)

        ' Add your code here
    End If

  End Sub

如果您需要所选项目在列表视图中的位置,您可以使用以下方法检索它:

  If Me.ListView1.SelectedIndices.Count > 0 Then
        Dim Pos As Integer = Me.ListView1.SelectedIndices(0)
  End If
于 2013-11-01T17:29:06.033 回答