vb.net 如何为组合框项添加值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1887388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:33:24  来源:igfitidea点击:

how to add value to combobox item

vb.net

提问by Utku Dalmaz

How can I add data value of each item to combobox in Visual Basic 2010?

如何将每个项目的数据值添加到 Visual Basic 2010 中的组合框?

Like html drop-down box.

像html下拉框。

Or is there anyway to add values to each item ?

或者无论如何要为每个项目添加值?

I am adding item from MySQL database like this:

我正在从 MySQL 数据库中添加项目,如下所示:

Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection)

Command.CommandTimeout = 30
Reader = Command.ExecuteReader()
If Reader.HasRows = True Then
    While Reader.Read()
        ComboBox1.Items.Add(Reader("name"))
    End While
End If

I need to add Reader("ID")as value of each item...

我需要添加Reader("ID")为每个项目的价值...

回答by dscarr

I am assuming that you are wanting to add items to a ComboBox on an Windows form. Although Klaus is on the right track I believe that the ListItem class is a member of the System.Web.UI.WebControls namespace. So you shouldn't be using it in a Windows forms solution. You can, however, create your own class that you can use in its place. Create a simple class called MyListItem (or whatever name you choose) like this:

我假设您想将项目添加到 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

Now when you want to add the items to your ComboBox you can do it like this:

现在,当您想将项目添加到 ComboBox 时,您可以这样做:

myComboBox.Items.Add(New MyListItem("Text to be displayed", "value of the item"))

Now when you want to retrieve the value of the selected item from your ComboBox you can do it like this:

现在,当您想从 ComboBox 中检索所选项目的值时,您可以这样做:

Dim oItem As MyListItem = CType(myComboBox.SelectedItem, MyListItem)
MessageBox.Show("The Value of the Item selected is: " & oItem.Value)

One of the keys here is overriding the ToString method in the class. This is where the ComboBox gets the text that is displayed.

这里的关键之一是覆盖类中的 ToString 方法。这是 ComboBox 获取显示文本的地方。



Matt made an excellent point, in his comment below, about using Generics to make this even more flexible. So I wondered what that would look like.

Matt 在下面的评论中提出了一个很好的观点,即使用泛型使其更加灵活。所以我想知道那会是什么样子。

Here's the new and improved GenericListItemclass:

这是新的和改进的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

And here is how you would now add Generic items to your ComboBox. In this case an Integer:

这是您现在将通用项目添加到 ComboBox 的方式。在这种情况下,一个整数:

Me.myComboBox.Items.Add(New GenericListItem(Of Integer)("Text to be displayed", 1))

And now the retrieval of the item:

现在检索项目:

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())

Keep in mind that the type Integercan be any type of object or value type. If you want it to be an object from one of your own custom classes that's fine. Basically anything goes with this approach.

请记住,类型Integer可以是任何类型的对象或值类型。如果您希望它是来自您自己的自定义类之一的对象,那很好。基本上任何事情都适用于这种方法。

回答by Yakov R.

Although this question is 5 years old I have come across a nice solution.

虽然这个问题已经有 5 年的历史了,但我遇到了一个很好的解决方案。

Use the 'DictionaryEntry' object to pair keys and values.

使用“DictionaryEntry”对象来配对键和值。

Set the 'DisplayMember' and 'ValueMember' properties to:

将“DisplayMember”和“ValueMember”属性设置为:

   Me.myComboBox.DisplayMember = "Key"
   Me.myComboBox.ValueMember = "Value"

To add items to the ComboBox:

要将项目添加到 ComboBox:

   Me.myComboBox.Items.Add(New DictionaryEntry("Text to be displayed", 1))

To retreive items like this:

要检索这样的项目:

MsgBox(Me.myComboBox.SelectedItem.Key & " " & Me.myComboBox.SelectedItem.Value)

回答by Tim Murphy

If you want to use SelectedValue then your combobox must be databound.

如果您想使用 SelectedValue,那么您的组合框必须是数据绑定的。

To set up the combobox:

要设置组合框:

ComboBox1.DataSource = GetMailItems()
ComboBox1.DisplayMember = "Name"
ComboBox1.ValueMember = "ID"

To get the data:

要获取数据:

Function GetMailItems() As List(Of MailItem)

    Dim mailItems = New List(Of MailItem)

    Command = New MySqlCommand("SELECT * FROM `maillist` WHERE l_id = '" & id & "'", connection)
    Command.CommandTimeout = 30
    Reader = Command.ExecuteReader()

    If Reader.HasRows = True Then
        While Reader.Read()
            mailItems.Add(New MailItem(Reader("ID"), Reader("name")))
        End While
    End If

    Return mailItems

End Function

Public Class MailItem

    Public Sub New(ByVal id As Integer, ByVal name As String)
        mID = id
        mName = name
    End Sub

    Private mID As Integer
    Public Property ID() As Integer
        Get
            Return mID
        End Get
        Set(ByVal value As Integer)
            mID = value
        End Set
    End Property

    Private mName As String
    Public Property Name() As String
        Get
            Return mName
        End Get
        Set(ByVal value As String)
            mName = value
        End Set
    End Property

End Class

回答by Klaus Byskov Pedersen

Instead of adding Reader("Name")you add a new ListItem. ListItemhas a Textand a Valueproperty that you can set.

而不是添加Reader("Name")您添加一个新的ListItem. ListItem有一个Text和一个Value你可以设置的属性。

回答by whyoz

Yeah, for most cases, you don't need to create a class with getters and setters. Just create a new Dictionary and bind it to the data source. Here's an example in VB using a for loop to set the DisplayMember and ValueMember of a combo box from a list:

是的,在大多数情况下,您不需要使用 getter 和 setter 创建一个类。只需创建一个新的 Dictionary 并将其绑定到数据源。这是 VB 中使用 for 循环从列表中设置组合框的 DisplayMember 和 ValueMember 的示例:

        Dim comboSource As New Dictionary(Of String, String)()
        cboMenu.Items.Clear()
        For I = 0 To SomeList.GetUpperBound(0)
            comboSource.Add(SomeList(I).Prop1, SomeList(I).Prop2)
        Next I
        cboMenu.DataSource = New BindingSource(comboSource, Nothing)
        cboMenu.DisplayMember = "Value"
        cboMenu.ValueMember = "Key"

Then you can set up a data grid view's rows according to the value or whatever you need by calling a method on click:

然后,您可以根据值或您需要的任何内容,通过在单击时调用方法来设置数据网格视图的行:

Private Sub cboMenu_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboMenu.SelectionChangeCommitted
    SetListGrid(cboManufMenu.SelectedValue)
End Sub

回答by Rinos

Now you can use insertmethod instead add

现在您可以改用insert方法add

' Visual Basic
CheckedListBox1.Items.Insert(0, "Copenhagen")