How do I set the column names in a DataTable as a datasource to a ComboBox?

tombihn

Member
Joined
Jan 17, 2011
Messages
10
Programming Experience
5-10
I'm trying to setup a form to search for data within an existing DataTable. Please help me fill in the blanks below:

FilterColumnsComboBox.DataSource = WOTable.Columns?
FilterColumnsComboBox.DisplayMember = ???
FilterColumnsComboBox.ValueMember = ???


I could hard-code in the column names ("WO_Number",WO_CustID","CustLastName", etc...), but would prefer to pick this up dynamically (partly because I want to reuse this code later).

Thanks in advance.
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,496
Location
Sydney, Australia
Programming Experience
10+
Are you saying that you want to display the column names from a DataTable in a ComboBox? If so then your DataSource is correct. The Columns property returns a DataColumnCollection, which contains DataColumn objects. The DataColumn class has a ColumnName property, which returns the name of the column. As such, both your DisplayMember and ValueMember should be "ColumnName".

By the way, you should almost universally set the DisplayMember and ValueMember before the DataSource.
 

tombihn

Member
Joined
Jan 17, 2011
Messages
10
Programming Experience
5-10
Thanks for the reply and the tip regarding best practices.

I am still getting the following error:
"Complex DataBinding accepts as a data source either an IList or an IListSource"


Here is my current code now:

            FilterColumns.DisplayMember = "ColumnName"
            FilterColumns.ValueMember = "ColumnName"
            FilterColumns.DataSource = woTable.Columns
 

jmcilhinney

VB.NET Forum Moderator
Staff member
Joined
Aug 17, 2004
Messages
14,496
Location
Sydney, Australia
Programming Experience
10+
That's interesting. I always assumed that the DataColumnCollection class, which is the type of DataTable.Columns, implemented the IList interface but, as it turns out, it only implements ICollection. That's bizarre because it actually does have an Item property.

Anyway, as the error message says, you need an IList in order to data-bind. An IListSource is simply a source for an IList, so it amounts to the same thing in the end. That's nice and easy, thanks to LINQ. Just change this:
FilterColumns.DataSource = woTable.Columns
to this:
FilterColumns.DataSource = woTable.Columns.Cast(Of DataColumn)().ToArray()
 
Top Bottom