Reputation: 26517
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
Upvotes: 1
Views: 1325
Reputation: 9599
I just found a cool solution to this same problem and I thought I'd put it here.
If you don't set the DisplayMemeber
the ComboBox will call the ToString method of yous source objects. So all you need to do is overriding the ToString
method, and voilá!
public override string ToString()
{
return string.Format("{0} - {1}", ID, Name);
}
Hope it helps!
Upvotes: 0
Reputation: 59645
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");
Upvotes: 1
Reputation: 31610
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
Upvotes: 0
Reputation: 55009
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.
Upvotes: 0