Thryn
Thryn

Reputation: 455

Fill a ComboBox with a DataSet

I'm trying to use a DataSet, filled from a SQL Database, that have only one column with unique names to fill ComboBoxes with.

Right now I'm using this code:

ClassTables.FillDistrib()
ComboBox.DataSource = ClassTables.Distrib.Tables("Names")

ClassTables is a Class used to fill my DataSets.
Distrib is the name of my DataSet (FillDistrib is the Sub used to clear and fill it)
ComboBox is the name of my ComboBox

But the ComboBox droplist is left blank.
However, used in a DataGridView, it appears that the DataSet is filled correctly.

Upvotes: 1

Views: 823

Answers (1)

Jimi
Jimi

Reputation: 32223

When assigning a complex object as a DataTable to the DataSource property of ComboBox or ListBox controls, specify, using the DisplayMember property, which Column of the DataTable should be used as source to display the text of the ListControl Items.

If the selected item should also return a value different from the text displayed, also set the ValueMember property to the name of the Column that provides the associated values.
Possibly, before setting the Control's DataSource reference (to avoid redundant iterations of the underlying data).

Let's build a DataTable to test the procedure:

Assign a DataTable to the DataSource of a ComboBox control, specifying as the DisplayMember the name of the Column that provides the text to display and as ValueMember the name of the Column that provides additional data that will be returned by the ComboBox.SelectedValue property when a user changes the SelectedItem:

Dim dt As New DataTable("TestTable")
dt.Columns.AddRange({
    New DataColumn("Names", GetType(String)), 
    New DataColumn("Values", GetType(Integer))
})

Dim row As DataRow = dt.NewRow()
dt.Rows.Add({"Some Name", 1})
dt.Rows.Add({"Some OtherName Jr.", 2})
dt.Rows.Add({"Another Name", 3})
dt.Rows.Add({"Last Name", 4})

ComboBox1.DisplayMember = "Names"
ComboBox1.ValueMember = "Values"
ComboBox1.DataSource = dt

Private Sub ComboBox1_SelectionChangeCommitted(sender As Object, e As EventArgs) Handles ComboBox1.SelectionChangeCommitted
    Dim cbo = DirectCast(sender, ComboBox)
    TextBox1.Text = cbo.GetItemText(cbo.SelectedValue)
End Sub

Result:

enter image description here

Upvotes: 2

Related Questions