1
votes

I have a combobox which is binded to a list. I've been trying to work out how to have the first item in the combobox when it's loaded a "--Please Select--" before the data from the list is loaded.

I have tried this,

        cbUpdate.DataSource = _names;
        cbUpdate.Items.Insert(0, "-Select-");
        cbUpdate.SelectedIndex = 0;
        cbUpdate.DisplayMember = "Name";

But this gives the errro,

Items collection cannot be modified when the DataSource property is set.

I understand the error, but I am unsure of how to solve it. I've trying to set the Text of the combobox to "Please Select" but that doesn't work.

var names = new BindingList<Names>();
4
If the data for this combo box is retreived through a Salad statement, add ˋ--- Please Select ---ˋ also as a value. Or remove the DataSource property and once you have all the dat retreived. Loop through the items and add values one by one, including the default optionSaagar Elias Jacky

4 Answers

3
votes

You are setting the DataSource and Adding an Item After which will eventually throw an error. A better approach would be to add the item "-Select-" first to the combobox then try to add next the items in the list using a foreach statement instead of binding the list to the combobox.

cbUpdate.Items.Clear();
cbUpdate.Items.Add("-Select-");

foreach (string item in thelsit)
{
  cbUpdate.Items.Add(item.ToString());
}

cbUpdate.SelectedIndex = 0;
0
votes

You have to decide, either use the Items property, and fill in all your options. Or use a DataSource with all the options.

In any case, for the "--Please Select--" entry, you either need to have it as one of the options inside the Items, or DataSource. Or you could just set the SelectedText property.

0
votes

Try inserting the '--Select--' text in the names list before setting it to the datasource.

Example:

List<Person> list = new List<Person>()  {
                                            new Person("Jon"),
                                            new Person("Ram"),
                                            new Person("Rin")                                       
                                         };

            list.Insert(0, new Person("--Select"));

            comboBox1.DataSource = list;
            comboBox1.DisplayMember = "Name";
            comboBox1.Items.Clear();
-1
votes

There are other ways to achieve this. It depends on how you are retrieving the values from your database.

If you are using a select statement, you can do a union like

// Oracle
SELECT 0, "---- Please Select ----" from dual 
 UNION
SELECT [value], [name] from [table] 

The result of which you can assign as the data source.

Another option is to remove the DataSource property and once you have the data in hand, iterate through the record set and add items one by one, with 0 and "---- Please Select ----" as the ValueMember and DisplayMember for the first item.