tags:

views:

493

answers:

2

hi

how can i add data value of each item to combobox in visual basic 2010.

like html drop-down box.

or is there anyway to add values to each item ?

i am adding item from mysql database like this

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...

thx

A: 

Instead of adding Reader("Name") you add a new ListItem. ListItem has a Text and a Value property that you can set.

klausbyskov
you mean listbox ? sorry i didnt understand, can you please show me short example ?
Ahmet vardar
+1  A: 

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

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
Tim Murphy
it works ! thanks and how can i get the selected item's value ?
Ahmet vardar
ok i figured it out, selectedvalue gets it, thank you again
Ahmet vardar