Pavel Oganesyan
Pavel Oganesyan

Reputation: 6924

Dynamically change items in comboBox

I have 2 comboBox objects with same items specified via Design redactor.

If any specific item is selected in the first comboBox, it must be removed from the second.

What I currently do:

1) Added this

static ComboBox.ObjectCollection defaultCollection;

2) On Form_Load

defaultCollection = comboBoxRange1.Items;

3)

private void comboBoxRange1_SelectedIndexChanged(object sender, EventArgs e)
{
    comboBoxRange2.Enabled = true;
    ComboBox.ObjectCollection copyCollection = defaultCollection;
    copyCollection.RemoveAt(comboBoxRange1.SelectedIndex);
    comboBoxRange2.DataSource = copyCollection;
}

But after this I got selected item removed from both comboBoxes and defaultCollection becomes modified. How do I fix it? Do I need to make copies of collections or manually reassemble values on every change?

Upvotes: 0

Views: 1581

Answers (2)

nevets
nevets

Reputation: 4818

ComboBox.ObjectCollection copyCollection = defaultCollection; doesn't do what you want it to do: it doesn't copy, but set a reference to defaultCollection.

Here are some more explanation on whether a variable is set by reference or set by value: if the data is a value type, basically struct and enumerations (say int, which is an alias of System.Int32), the value of the data will be copied when doing an assignment; if the data is a reference type, basically classes, interfaces and delegates, the reference to the object will be passed to the LHS when doing an assignment.

As for your question, yes, you need to make a copy to keep defaultCollection unmodified.

Upvotes: 1

Coding Flow
Coding Flow

Reputation: 21881

You are not creating a copy of the collection, you are simply creating a new variable that references the same collection as the first. It does not matter which variable you use to remove the item, you still have only one collection referenced by 2 variables and bound to 2 combo boxes.

Upvotes: 1

Related Questions