Controls:
ComboBox:
Functions:
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
Functions:
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);
}
}
}
Now lets say I select item A on ComboBox so the CheckedListBox have now Collection Items Q. I check 2 items from Q and then I select different item from ComboBox B so the Collection Items of CheckedListBox (W) change too. Now if I go back to A, the Collection Items Q is again retrieved back. I want now the 2 items that I checked to be retrieved too. How I can do that?
My idea was something like that (I add this code inside cbSubCategories_SelectedIndexChanged at the end) but it throws this exception 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++;
}
why don't you do it upon SelectedIndexChanged
event of your comboBox. That's where you are re-binding everytime your CheckedListBox.
so inside AddSubCategories2(int from, int to)
, after adding items to your CheckedListBox, again iterate through the items of it and mark all those which exist in the checkedItems list.
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);
}
}