【发布时间】:2013-03-12 20:40:31
【问题描述】:
控件:
- 1 个组合框
- 1 CheckedListBox
组合框:
- 项目:110
- 事件:
- SelectedIndexChanged:每次选中索引改变CheckedListBox的items集合变化
功能:
private void cbSubCategories_SelectedIndexChanged(object sender, EventArgs e)
{
switch(cbSubCategories.Text)
{
clbSubCategories2.Items.Clear();
case "Category 1":
AddSubCategory(0, 15);
break;
//etc.
}
}
private void AddSubCategories2(int from, int to)
{
for (int i = from; i < to; i++)
clbSubCategories2.Items.Add(strSubCategories2[i]);
}
检查列表框
- 项目:取决于在 ComboBox 中选择的项目
- 事件:
- ItemCheck:将选中的项目添加到列表中
功能:
List<string> checkedItems = new List<string>();
private void clbSubCategories2_ItemCheck(object sender, ItemCheckEventArgs e)
{
int idx = 0;
if (e.NewValue == CheckState.Checked)
checkedItems.Add(clbSubCategories2.Items[e.Index].ToString());
else if (e.NewValue == CheckState.Unchecked)
{
if (checkedItems.Contains(clbSubCategories2.Items[e.Index].ToString()))
{
idx = checkedItems.IndexOf(clbSubCategories2.Items[e.Index].ToString());
checkedItems.RemoveAt(idx);
}
}
}
现在假设我在 ComboBox 上选择了项目 A,所以 CheckedListBox 现在有 Collection Items Q。我检查了 Q 中的 2 个项目,然后我从 ComboBox B 中选择了不同的项目,因此 CheckedListBox (W) 的集合项目也发生了变化。现在,如果我返回 A,Collection Items Q 会再次被检索回来。我现在也想检索我检查的 2 个项目。我该怎么做?
我的想法是这样的(我在最后的 cbSubCategories_SelectedIndexChanged 中添加了这段代码)但它抛出了这个异常Collection was modified; enumeration operation may not execute.:
int x = 0;
foreach (string item in clbSubCategories2.Items)
{
foreach (string item2 in checkedItems)
{
if (item2 == item)
clbSubCategories2.SetItemChecked(x, true);
}
x++;
}
【问题讨论】:
标签: c# winforms combobox checkedlistbox