控制:
- 1 个组合框
- 1 选中列表框
组合框:
- 项目: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++;
}