VB.NET中的列表框

时间:2010-09-29 06:46:06

标签: vb.net winforms listbox

我想在ListBox中手动添加两个项目“Active”和“Inactive”。当用户选择“活动”时,我想获得值“A”,当选择“非活动”时,我想得到“我”。

我如何在VB.NET中执行此操作。

3 个答案:

答案 0 :(得分:1)

您使用的是.NET 4吗?如果是这样,最简单的解决方案可能是使用Tuple(Of String, String)。创建一个(“活动”,“A”)和另一个(“非活动”,“我”)的元组,并将它们添加到列表框中。然后将列表框的DisplayMember属性设置为“Item1”,将ValueMember设置为“Item2”。

或者你可以用匿名类型做同样的事情。

答案 1 :(得分:0)

ListboxItemCollection的类型为Object。您可以像这样创建一个自定义ListItem

Public Class Form1

    Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        BindListBox()
    End Sub

    Private Sub BindListBox()
        With ListBox1
            .Items.Add(New CustomListItem("Acitve", "A"))
            .Items.Add(New CustomListItem("Inactive", "I"))
            .DisplayMember = "Text"
        End With
    End Sub

    Private Sub ListBox1_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
        MsgBox(CType(ListBox1.SelectedItem, CustomListItem).Value)
    End Sub

End Class


''Custom ListItem Class
Public Class CustomListItem
    Dim _text As String
    Dim _value As String

    Sub New(ByVal text As String, ByVal value As String)
        Me._text = text
        Me._value = value
    End Sub

    Public ReadOnly Property Text() As String
        Get
            Return _text
        End Get
    End Property

    Public ReadOnly Property Value() As String
        Get
            Return _value
        End Get
    End Property
End Class

答案 2 :(得分:0)

一个简单的选项

Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
    Debug.Print(ListBox1.Items(ListBox1.SelectedIndex).ToString.Substring(0, 1))
End Sub