Add an empty item to the combobox associated with the entity list.

c# combobox data-binding entity-framework winforms

Question

I use a ComboBox which is bound to a List<> of Entities. How can I add a "Not selected" entry to the combobox? Adding null to the list results in empty combobox.

1
8
9/7/2009 10:36:13 AM

Accepted Answer

You should use an empty string or other unique text pattern instead of null.

And then You can handle the Format event of the Combobox to intercept the <empty> and display an alternate text.

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;
}
2
9/7/2009 11:59:41 AM

Popular Answer

If you're binding to IEnumerable list of entities you can certainly add your empty object manually.

For example

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"


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow