如何在列表框中获取项目的索引位置并返回位置编号而不是字符串?我尝试返回索引位置,但我的代码只返回字符串而不是位置编号,这是我的代码
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")
任何人都可以帮我如何返回索引位置编号吗?
答案 0 :(得分:1)
因为,索引是从零开始的,所以你需要+1
SelectedIndex
,如下所示:
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()
一个字符串,因为它已经是一个字符串。
答案 1 :(得分:1)
我建议您将Listbox
更改为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