简体   繁体   English

动态更改comboBox中的项目

[英]Dynamically change items in comboBox

I have 2 comboBox objects with same items specified via Design redactor. 我有2个comboBox对象,它们具有通过Design redactor指定的相同项目。

If any specific item is selected in the first comboBox, it must be removed from the second. 如果在第一个comboBox中选择了任何特定项目,则必须将其从第二个comboBox中删除。

What I currently do: 我目前正在做什么:

1) Added this 1)添加了

static ComboBox.ObjectCollection defaultCollection;

2) On Form_Load 2)在Form_Load

defaultCollection = comboBoxRange1.Items;

3) 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. 但是在此之后,我将选择的项目从comboBoxes中删除,并且defaultCollection被修改。 How do I fix it? 我如何解决它? Do I need to make copies of collections or manually reassemble values on every change? 我是否需要复制集合或在每次更改时手动重新组合值?

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. 使用哪个变量删除项目都没有关系,您仍然只有一个由2个变量引用并绑定到2个组合框的集合。

ComboBox.ObjectCollection copyCollection = defaultCollection; doesn't do what you want it to do: it doesn't copy , but set a reference to defaultCollection . 不执行您想要的操作:不复制 ,但设置对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; 以下是有关变量是通过引用 设置还是由值 设置的更多解释:如果数据是值类型 ,基本上是struct和枚举(例如int ,它是System.Int32的别名),则数据的将在做作业时被复制 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. 如果数据是引用类型 (基本上是类,接口和委托),则对对象的引用将在进行分配时传递给LHS。

As for your question, yes, you need to make a copy to keep defaultCollection unmodified. 对于您的问题,是的,您需要进行复制以保持defaultCollection不变。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM