Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add empty entry to combobox bound to entity list

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.

like image 278
wRAR Avatar asked Sep 07 '09 10:09

wRAR


2 Answers

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"
like image 86
keith Avatar answered Oct 06 '22 14:10

keith


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;
}
like image 37
Henk Holterman Avatar answered Oct 06 '22 14:10

Henk Holterman