将空条目添加到绑定到实体列表的组合框中

wRA*_*RAR 8 c# data-binding combobox entity-framework winforms

我使用一个ComboBox,它绑定到List <> of Entities.如何在组合框中添加"未选中"条目?将null添加到列表会导致空组合框.

kei*_*ith 7

如果您绑定到IEnumerable实体列表,您当然可以手动添加空对象.

例如

var qry = from c in Entities
          select c;
var lst = qry.ToList();

var entity = new Entity();
entity.EntityId= -1;
entity.EntityDesc = "(All)";
lst.Insert(0, entity);

MyComboBox.DataSource = lst;
MyComboBox.DisplayMember = "EntityDesc"
MyComboBox.ValueMember = "EntityId"
Run Code Online (Sandbox Code Playgroud)


Hen*_*man 2

您应该使用空字符串或其他唯一的文本模式而不是 null。

然后您可以处理 Combobox 的 Format 事件来拦截<empty>并显示替代文本。

private void comboBox1_Format(object sender, ListControlConvertEventArgs e)
{
   e.Value = FormatForCombobox(e.ListItem);
}


private string FormatForCombobox(object value)
{
  string v = (string) value;
  if (v == string.Empty)
     v = "<no Selection>";
  return v;
}
Run Code Online (Sandbox Code Playgroud)