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

c# combobox data-binding entity-framework winforms

Question

I employ a ComboBox connected to a List of Entities. How can I make the combobox include a "Not chosen" entry? A combobox that contains null is empty when added to the list.

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

Accepted Answer

Null should be replaced by an empty string or any other distinctive text pattern.

After that, you may manage the Combobox's Format event to snare the<empty> and show a different 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 committed toIEnumerable You may surely manually add your empty object to the list of entities.

For instance

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