How to insert item at the top of Combo Box?

18,251

Solution 1

One way would be to insert the "--Select--" contact place-holder into the results before binding:

     var items = (from c in db.Contacts
                  orderby c.Name ascending
                  select c).ToList();

     items.Insert(0, new Contact { ID = 0, Name = "--Select--" });

     cmb1.BindingContext = new BindingContext();
     cmb1.DataSource = items;
     cmb1.DisplayMember = "Name";
     cmb1.ValueMember = "ID";

Or you could do the same thing with an anonymous version of the results:

     var items = (from c in db.Contacts
                  orderby c.Name ascending
                  select new { c.ID, c.Name }).ToList();

     items.Insert(0, new { ID = 0, Name = "--Select--" });

     cmb1.BindingContext = new BindingContext();
     cmb1.DataSource = items;
     cmb1.DisplayMember = "Name";
     cmb1.ValueMember = "ID";

Solution 2

As you noted in your own comment to your question, you can't insert an item after data binding.

One option would be to use Concat to concatenate a sequence containing your "Select" item with the results of your query.

Share:
18,251
User13839404
Author by

User13839404

Updated on June 04, 2022

Comments

  • User13839404
    User13839404 almost 2 years

    Hi I am using Linq to SQl to bind the combo box control. How can i add a item at the top of the list of combo box?

    var items = from c in db.Contacts
                                   orderby c.Name ascending
                                   select c;
                    if (items.ToList().Count > 0)
                    {
                        cmb1.BindingContext = new BindingContext();
                        cmb1.DataSource = items;
                        cmb1.DisplayMember = "Name";
                        cmb1.ValueMember = "ID";
                    }
    
                    cmb1.Items.Insert(0, "--Select--");
    

    This above code is failing.