我如何绑定一个组合框,以便displaymember是源数据表的2个字段的连接? [英] How do I bind a ComboBox so the displaymember is concat of 2 fields of source datatable?
问题描述
我想将 ComboBox
绑定到 DataTable
(我无法更改其原始架构)
I'd like to bind a ComboBox
to a DataTable
(I cannot alter its original schema)
cbo.DataSource = tbldata;
cbo.DataTextField = "Name";
cbo.DataValueField = "GUID";
cbo.DataBind();
我希望 ComboBox
显示 tbldata.Name + tbldata.Surname
。
当然,将新名称和姓氏作为字段添加到 tbldata
可以在绑定之前使用,但我希望按照(伪代码)寻求更优雅的解决方案
Of course adding the new name+surname as a field to the tbldata
just before binding is possible, but I am hoping for a more elegant solution along the lines of (pseudocode)
cbo.DataTextField = "Name";
cbo.DataTextField += "Surname";
推荐答案
计算列解决方案可能是最好的。但是,如果您不能更改数据表的架构来添加它,则可以遍历该表并填充将用作数据源的新集合。
The calculated column solution is probably the best one. But if you can't alter the data table's schema to add that, you can loop through the table and populate a new collection that will serve as the data source.
var dict = new Dictionary<Guid, string>();
foreach (DataRow row in dt.Rows)
{
dict.Add(row["GUID"], row["Name"] + " " + row["Surname"]);
}
cbo.DataSource = dict;
cbo.DataTextField = "Value";
cbo.DataValueField = "Key";
cbo.DataBind();
显然,这不像直接绑定到DataTable那样高效,但是我不必为此担心除非表有数千行。
Obviously this isn't as performant as binding directly to the DataTable but I wouldn't worry about that unless the table has thousands of rows.
这篇关于我如何绑定一个组合框,以便displaymember是源数据表的2个字段的连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!