OK, I've exhausted my searching, so if someone can point me to a link with a good example, that would be super.

I'm simply trying populate a combobox with data from an Access table (it's a simple contact list with Name and Number). Every example I find and try, I get something that goes wrong. I can get the table imported with a SINGLE column, but need both columns displayed with the selected choice being the number column.

 Sub FillComboBox()
        Dim con As OleDbConnection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=contacts.accdb")
        Dim cmd As OleDbCommand = New OleDbCommand("SELECT * FROM ContactData ORDER BY ContactName ASC", con)
        con.Open()
        Dim sdr As OleDbDataReader = cmd.ExecuteReader
        While sdr.Read()
            cbo_To.Items.Add(sdr.Item("ContactName").ToString)
        End While

        con.Close()
        con = Nothing
 End Sub

I can concatenate with something like cbo_To.Items.Add(sdr.Item("ContactName").ToString + " " + sdr.Item("ContactNumber".ToString)), but I really only want the Number in the field.

Thanks

Recommended Answers

All 3 Replies

Use a datatable to bind your combobox to and set display and value members:

    Dim conn As New OleDb.OleDbConnection("Your string here")
    Dim comm As New OleDb.OleDbCommand
    Dim table As New DataTable
    Dim data As New OleDb.OleDbDataAdapter
    comm.Connection = conn
    comm.CommandText = "select id,  id & ' ' &  test as test from Table1 "
    data.SelectCommand = comm
    data.Fill(table)

    ComboBox1.DisplayMember = "test"
    ComboBox1.ValueMember = "id"

    ComboBox1.DataSource = table

When you want to use the number (id in my example) you can like this: MsgBox(ComboBox1.SelectedValue) and you can get whatever user is seeing like this: MsgBox(ComboBox1.Text)

I thought multi-column comboboxes were not supported natively in vb.net without subclassing and custom code.

Thank you very much Adam. That works nearly perfectly. I tried it and it gives me exactly what I was looking for. I can certainly get by with what you provided.

The only thing is, the multicolumn part of it isn't as "neat" as I would like to see. I think Jim is correct that you need a class or some other way to do neat looking multiple columns. I found this link: Click Here which is the look that I want, however, I'm going to look for other examples to see if it can be incorporated into the code you gave me.

Thanks again!

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.