c# - 如何绑定(bind) ComboBox 以便 displaymember 是源数据表的 2 个字段的 concat?

标签 c# data-binding combobox

我想将一个 ComboBox 绑定(bind)到一个 DataTable (我不能改变它的原始模式)

cbo.DataSource = tbldata;
cbo.DataTextField = "Name";
cbo.DataValueField = "GUID";
cbo.DataBind();

我想要 ComboBox 显示 tbldata.Name + tbldata.Surname

当然,在绑定(bind)之前将新名称+姓氏作为字段添加到 tbldata 是可能的,但我希望有一个更优雅的解决方案(伪代码)

cbo.DataTextField = "Name";
cbo.DataTextField += "Surname";

最佳答案

计算出的色谱柱解决方案可能是最好的。但是,如果您无法通过更改数据表的架构来添加它,则可以遍历该表并填充一个将用作数据源的新集合。

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

显然,这不如直接绑定(bind)到 DataTable 那样高效,但我不会担心这一点,除非该表有数千行。

关于c# - 如何绑定(bind) ComboBox 以便 displaymember 是源数据表的 2 个字段的 concat?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1006521/

相关文章:

c# - 在属性更改时触发 ListViewItem 行为?

.net - DataGrid 数据绑定(bind)/更新中的 WPF 组合框不起作用

c# - 如何使用 C# 从 FTP 服务器获取一系列文件

c# - 使用 linq 和 lambdas 的多分隔字符串到对象列表

c# - 将多个 DataBindings 添加到 Winforms 标签

c# - Blazor 将数据绑定(bind)到集合?

c# - 控件不在焦点时下拉列表更改所选值

c# - WPF ComboBox 绑定(bind)未正确更新

c# - 对象引用未设置为对象的实例 #3

c# - .Net/C# 反射--填充组合框