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

荒凉一梦 提交于 2019-12-24 10:19:42

问题


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


回答1:


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



回答2:


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.




回答3:


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




回答4:


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!



来源:https://stackoverflow.com/questions/2843823/net-how-can-i-have-a-combobox-with-multitple-fields-of-its-data-source-as-disp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!