KJ3
KJ3

Reputation: 5298

Loading a Combobox with a DataSet and Loading a Default Value

I'm creating a Windows Form application in C# and am sort of translating it from and asp.net forms application. I'm running into a difference I can't seem to get an answer on. I have loaded a combobox with items from a dataset but I would like the first item to say Select... or something like that rather than just show the first item from the dataset. In asp.net, I would just say

ddSelected.Items.Insert(0, "Select...");

But here I get an error: Items collection cannot be modified when the DataSource property is set.

How can I do this in C# for Windows Forms?

Upvotes: 0

Views: 1386

Answers (1)

Mash
Mash

Reputation: 1536

This solution may point you in the right direction, but it all depends on exactly what your DataSource object type is.

Imagine a scenario such as this:

    BindingList<string> myList = new BindingList<string>();
    myList.Add("Mark");
    myList.Add("Joe");
    myList.Add("Kelly");
    myList.Add("Susan");
    comboBox1.DataSource = myList;

All you would have to do is update your myList and the ComboBox items will update:

    myList.Insert(0, "Select...");

Note that this will work seamlessly with a BindingList because it implements IRaiseItemChangedEvents.

If your underlying DataSource is an object such as an ArrayList, then in order to "Refresh" the ComboBox items, you would need to do something like:

    comboBox1.DataSource = null;
    comboBox1.DataSource = myList;

This is because the ArrayList class doesn't inherently raise events to notify any bound controls that the collection has changed.

  1. Update your underlying datasource.
  2. If necessary, update your ComboBox Datasource property by setting it null and back to your underlying datasource.

Upvotes: 1

Related Questions