Question

Having a problem with this Winforms project. Trying to use the SelectedIndexChanged event on a combBox that that was populated with the dictionary propList via:

comboBox1.DataSource = new BindingSource(propList, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

This is the event itself:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    ComboBox comboBox = (ComboBox)sender;
    //comboBox.DataSource = null;
    System.Collections.Generic.KeyValuePair<int, string> dummy =
        (System.Collections.Generic.KeyValuePair<int, string>) 
            comboBox.SelectedItem;

    //comboBox1.DataSource = new BindingSource(propList, null);
    PopulateCollars(dummy.Key);
}

It then throws this on the KeyValuePair cast:

Items collection cannot be modified when the DataSource property is set

I know this is the appriopriate cast, since debugging shows that:

SelectedItem  ~~~  object System.Collections.Generic.KeyValuePair<int,string>}

My question is then, why does an explicit cast modify the items collection? Being brought up on C++, where casts do not modify the data they are casting, this doesn't make sense to me.

As a note, using the lines commented out causes a null reference exception since apparently setting the data source to null wipes all members in the comboBox.

Was it helpful?

Solution

By any chance, are you modifying either dummy.Key or dummy itself in PopulateCollars? Since I've never seen a cast change the data of an object either, that routine seems more likely to be the culprit. As I commented above, sometimes VS is just plain wrong about what line threw the error.

ETA: Okay, that's not it. Here's an idea. Examine the stack trace of the exception, and see whether there's any interesting layers between your method and the method that (in the framework) threw the exception. Also make sure that this method is not being recursively invoked through something in PopulateCollars that causes the list to change.

If you are trying to reuse the same combo box with other data while handling a change caused by the combo box, that probably won't work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top