我有以下代码:
private void LoadCombos()
{
//
//Entity
cmbEntity.ValueMember = "ID";
cmbEntity.DisplayMember = "Name";
cmbEntity.DataSource = store.Entities; //store is an objectContext
//
}
我正在尝试使用以下方式显示Name和ID:
cmbEntity.DisplayMember = "ID+Name";
有没有办法实现这一点,以便在组合框中显示ID和名称?
答案 0 :(得分:2)
试试这个:
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
。
答案 1 :(得分:0)
类似于此问题已经回答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();