我假设你是想将项目添加到组合框的Windows窗体上。虽然Klaus在正确的轨道上,我相信ListItem类是System.Web.UI.WebControls命名空间的成员。所以你不应该在Windows窗体解决方案中使用它。但是,您可以创建自己的班级,您可以使用它。 创建一个名为MyListItem(或任何名称你选择),这样简单的类:
Public Class MyListItem
Private mText As String
Private mValue As String
Public Sub New(ByVal pText As String, ByVal pValue As String)
mText = pText
mValue = pValue
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
Public ReadOnly Property Value() As String
Get
Return mValue
End Get
End Property
Public Overrides Function ToString() As String
Return mText
End Function
End Class
现在,当您想将项目添加到您的组合框,你可以做这样的:
myComboBox.Items.Add(New MyListItem("Text to be displayed", "value of the item"))
现在当你想要从你的ComboBox中所选项目的值,你可以做这样的:
Dim oItem As MyListItem = CType(myComboBox.SelectedItem, MyListItem)
MessageBox.Show("The Value of the Item selected is: " & oItem.Value)
的关键之一这里覆盖的ToString方法类。这是ComboBox获取显示的文本的位置。
Matt在下面的评论中提到了使用泛型使其更加灵活的优点。所以我想知道会是什么样子。
这里是新的和改进GenericListItem
类:
Public Class GenericListItem(Of T)
Private mText As String
Private mValue As T
Public Sub New(ByVal pText As String, ByVal pValue As T)
mText = pText
mValue = pValue
End Sub
Public ReadOnly Property Text() As String
Get
Return mText
End Get
End Property
Public ReadOnly Property Value() As T
Get
Return mValue
End Get
End Property
Public Overrides Function ToString() As String
Return mText
End Function
End Class
这里是你会怎么现在通用的项目到您的组合框添加。在这种情况下,一个整数:
Me.myComboBox.Items.Add(New GenericListItem(Of Integer)("Text to be displayed", 1))
而现在该项目的检索:
Dim oItem As GenericListItem(Of Integer) = CType(Me.myComboBox.SelectedItem, GenericListItem(Of Integer))
MessageBox.Show("The value of the Item selected is: " & oItem.Value.ToString())
记住类型Integer
可以是任何类型的对象或值类型的。如果你想让它成为你自己的自定义类中的一个对象,那很好。基本上任何事情都会采用这种方法。
在vb.net 2015 dosen't work :( – Rinos 2017-06-22 13:05:09