控制:
组合框:
功能:
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]);
}
CheckedListBox
功能:
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现在拥有收集项 Q 。我检查了 Q 中的2个项目,然后从ComboBox B 中选择了不同的项目,因此CheckedListBox的收集项目( W )也会发生变化。现在,如果我返回 A ,则会再次检索收集项 Q 。我现在想要检查的两件物品也要检索。我怎么能这样做?
我的想法是这样的(我在最后的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++;
}
答案 0 :(得分:1)
为什么不在comboBox的SelectedIndexChanged
事件中执行此操作。这就是每次CheckedListBox重新绑定的地方。
所以在AddSubCategories2(int from, int to)
内,在将项添加到CheckedListBox之后,再次迭代它的项并标记checkedItems列表中存在的所有项。
private void AddSubCategories2(int from, int to)
{
for (int i = from; i < to; i++)
clbSubCategories2.Items.Add(strSubCategories2[i]);
if(checkedItems!=null)
foreach(string item in checkedItems)
{
int index= clbSubCategories2.FindStringExact(item);
if(index>-1)
clbSubCategories2.SetItemChecked(index, true);
}
}