如何绑定 ComboBox 以便显示成员连接源数据表的 2 个字段? [英] How do I bind a ComboBox so the displaymember is concat of 2 fields of source datatable?

查看:9
本文介绍了如何绑定 ComboBox 以便显示成员连接源数据表的 2 个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将 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.

这篇关于如何绑定 ComboBox 以便显示成员连接源数据表的 2 个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆