【问题标题】:How to display combination of columns as display member?如何将列组合显示为显示成员?
【发布时间】:2014-01-29 05:23:40
【问题描述】:

我有以下代码:

private void LoadCombos()
{
    //
    //Entity
    cmbEntity.ValueMember = "ID";
    cmbEntity.DisplayMember = "Name";
    cmbEntity.DataSource = store.Entities; //store is an objectContext
    //
}

我正在尝试使用这个来显示名称和 ID:

cmbEntity.DisplayMember = "ID+Name";

有没有办法实现这一点,以便在组合框中显示 ID 和名称?

【问题讨论】:

  • 这样不行,得更新datasource中的数据。

标签: c# winforms entity-framework edmx


【解决方案1】:

试试这个:

cmbEntity.DataSource =
             store.Entities
                     .ToList()
                     .Select(e => new {Id = e.Id, Name = e.Id + e.Name});

或者你可以使用

cmbEntity.DataSource =
     store.Entities
          .Select(e => new {Id = e.Id,
                     Name = SqlFunctions.StringConvert((decimal)e.Id + e.Name});

在这种情况下,您必须添加对程序集 System.Data.Entity.dll 的引用并导入命名空间 System.Data.Objects.SqlClient

【讨论】:

  • @PrakashVishwakarma 添加ToList() 结束。使用代码时是否填充了组合?
  • No combo 没有填充任何数据,也尝试了 ToList
  • 是的,它使用我在问题 cmbEntity.DataSource = store.Entities; 中提到的现有代码填充数据
  • 它给出错误:无法将类型“System.Int64”转换为类型“System.Object”。 LINQ to Entities 仅支持转换 EDM 基元或枚举类型。
  • 以上都不起作用,即使在您新更新的更改之后。
【解决方案2】:

here 已经回答了与此问题类似的问题,其中包含您可以使用 Dictionary 实现它的方法之一

var dict = new Dictionary<Guid, string>();
foreach (var row in dt.Rows)
{
    dict.Add(row["GUID"], row["Name"] + " " + row["Surname"]);
}
cbo.DataSource = dict;
cbo.DataTextField = "Value";
cbo.DataValueField = "Key";
cbo.DataBind();

【讨论】:

  • Combobox 没有 DataTextField 和 DatavalueField 属性
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-05
  • 2013-07-26
  • 2013-04-18
相关资源
最近更新 更多