tags:

views:

27

answers:

3

hi

How can I have a combobox with multiple fields of its data source as its display member without adding additional columns to its data source?

I mean I wanna to have a combobox with displaymember like "ID" + "-" "Name" . 1 - Black 2 - White 3 - Red

I DO NOT want to add additional column to its data source.

Thank you

A: 

Use a select statement to get out the data rather than just get everything from the table and write something like:

SELECT ID, STR(ID) + ' - ' + Name DisplayName FROM table1

Then set ID as the data member and DisplayName as the display member.

Untested, but feels like it should work.

ho1
+1  A: 

Binding to multiple properties is not supported (in WinForms). You have to extend your DataTable with a computed column and bind to this new column.

dataTable.Columns.Add("IdAndName", typeof(String), "ID + Name");

comboBox.DataSource = dataTable;
comboBox.DisplayMember = "IdAndName";

See the MSDN for reference on valid expressions for computed columns. Maybe you have to use Convert.

dataTable.Columns.Add("IdAndName", typeof(String), "Convert(ID, 'System.String') + Name");
Daniel Brückner
A: 

Options:
1) Modify your Data Call to include the combined column, i.e. you wouldn't be "adding" a column per se, you'd be selecting the two columns as stated by ho
2) Switch to a ListView
3) Add the results of your data call to a collection class which has the fields you want to display (ID, DisplayName) and add a "IDDisplayNameCombined" property which combines them and bind this collection to the combobox and use the new combined property as the displaymember

RandomNoob