trant trum trant trum - 2 years ago 78 Question

How to add data table items in a combo box?

I have a function which return a list of countries as data table. How do I add these row values to a combo box?

For Each row as DataRow in fooDataTable.Rows

Some how this does not fill up the values on my combo box. The datatable returns 100 rows. Each row has 2 columns. I am trying to add all the 100 datarows with the first column. Any help would be greatly appreciated.

Answer Source

A DataRow is an object and while objects can be added to a Combo or ListBox, in this case the result is not very useful. When you store an Object in .Items, the result of the .ToString function is what displays. In this case it will just display System.Data.Datarow

The best solution is what LarsTech suggested and use the existing datatable as the datasource. This is economical because there is nothing new created for the CBO:

ComboBox.DataSource = fooDataTable 
ComboBox.DisplayMember = "column name in DT"

Another way is to modify your loop:

combobox.Items.Add(row("col name").ToString)

This adds the data from the column name to the cbo. If this was something like peoples names and you wanted to show First and Last name:

combobox.Items.Add(String.Format("{0}, {1}", row("LastName").ToString,

This is similar except we are formatting the contents of both columns as we add it to the CBO.

Still another way is to create a class object for each row which returns what you want to display via the ToString override; and add them to the CBO, but that is overkill in this case, given the economy of the first alternative.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download