Corbin de Bruin
Corbin de Bruin

Reputation: 35

vb.net Bind a combobox to a datasource

Over the past few days, I've read about a thousand forum posts, and looked at many code samples, but I still can't figure this out.

My goal is to populate a combobox with values from an Access 2007 query. I can do this by using the DataSource, DisplayMember and ValueMember properties, but regardless of the data in the query, the comboboxes all just default to the to first item in the items collection and don't change when the main BindingSource is moved. I am binding the controls with this line of code:

 ComboBox1.DataSource = DataSet1.qryItemSourceTest
 ComboBox1.DisplayMember = "SourceTestDisplayField"
 ComboBox1.ValueMember = "SourceTestIDField"
 Combobox1.DataBindings.Add(New Binding("SelectedValue", qryTestBindingSource, "TestField", True))

I have also tried using a BindingSource as a DataSource. I have also tried using an array as a DataSource.

If I drag the control on from the Data Source tab in the IDE, it will scroll through records properly, but it will only display the value and not the query 'look-up' value that I want the combobox to display. I have tried changing the DisplayMember and ValueMember properties of the combobox after dragging it on from the Data Sources tab and that seems to break the functionality as well.

I'm looking for some best practices here. I know I'm missing something easy here and I apologize for post an issue that has already been covered so many times, but I could use some individual help here.

Edit: I eventually was able to accomplish my goal using the Visual Studio IDE Properties window. The second property on a control is a Data Bindings property which expands into exactly what I needed. I just never saw this before because it was not in alphabetically order like everything else.

Upvotes: 1

Views: 14639

Answers (1)

SMHasnain
SMHasnain

Reputation: 706

Hi you can do this code to populate data into combo

Try

        Dim cn As New OleDbConnection
        cn.ConnectionString = conString
        cn.Open()

        cmd.Connection = cn
        cmd.CommandText = "your query"

        'Execte reader function is used to hold more than one value from the table
        dr = cmd.ExecuteReader()


        ' Fill a combo box with the datareader
        Do While dr.Read = True
            ComboBox1 = dr.Item(0)
        Loop

        cn.Close()

    Catch ex As Exception
        MsgBox(ex.Message)

    End Try

If you have any more problems don't hesitate to ask.

Upvotes: 1

Related Questions