【发布时间】:2010-09-29 06:46:06
【问题描述】:
我想在 ListBox 中手动添加两个项目作为“活动”和“非活动”。当用户选择“ Active”时,我想获得值“ A”,并且选择“无活动”时,我想获得“ I”。
我如何在 VB.NET 中做到这一点。
【问题讨论】:
我想在 ListBox 中手动添加两个项目作为“活动”和“非活动”。当用户选择“ Active”时,我想获得值“ A”,并且选择“无活动”时,我想获得“ I”。
我如何在 VB.NET 中做到这一点。
【问题讨论】:
您使用的是 .NET 4 吗?如果是这样,最简单的解决方案可能是使用Tuple(Of String, String)。创建一个 ("Active", "A") 元组和另一个 ("Inactive", "I") 元组,并将它们添加到列表框中。然后将列表框的DisplayMember 属性设置为“Item1”,将ValueMember 设置为“Item2”。
或者你可以对匿名类型做同样的事情。
【讨论】:
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
【讨论】:
一个简单的选择
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
【讨论】: