开发者

.Net: how can I have a combobox with multitple fields of its data source as Displaymember?

How can I have a combobox with multiple fields of its data source as its display member without 开发者_Go百科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


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");


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.


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


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜