我假设您想要将项目添加到 Windows 窗体上的 ComboBox。尽管 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
现在,当您想将项目添加到您的 ComboBox 时,您可以这样做:
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 类型可以是任何类型的对象或值类型。如果您希望它成为您自己的自定义类之一的对象,那很好。基本上任何事情都适用于这种方法。