P.C P.C - 1 month ago 18
C# Question

C# Item in checkedListBox gets selected even though box is unchecked

If I have an item that I check and then I decide to uncheck, the code somewhat believes it is still checked. The result is that when I click "Go" the table also lists the unchecked item. In this case, Brandon was first checked, then unchecked. Even though the name is no longer "checked", the table still brings it up.

Item still checked

This is what I have:

string filterstring = "";
private void checkedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Checked)
filterstring = "Responsible = '" + checkedListBox.Items[e.Index].ToString() + "' OR";
else


if (e.NewValue == CheckState.Unchecked)
filterstring = "";


foreach (object itemChecked in checkedListBox.CheckedItems)
{
filterstring += " Responsible = '" + itemChecked.ToString() + "' OR";
}
filterstring = filterstring.Substring(0, filterstring.LastIndexOf("OR"));
}


I suspect that the key is in this part of the code. Without it, it throws an exception:

private void checkedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
if (e.NewValue == CheckState.Unchecked)
filterstring = "";
}


Any helps is appreciated!

Answer

The list of checked items isn't updated until after the ItemCheck event is fired, so your for-each loop is not reporting accurate checked items.

To avoid that, use a BeginInvoke call:

  this.BeginInvoke(new Action(() => {
    foreach (var itemChecked in checkedListBox1.CheckedItems) {
      filterString += itemChecked.ToString();
    }
  }));

This code will basically run immediately after the ItemCheck event method is called.

Update:

Since you are getting an exception on the SubString code, try creating your filter text like this:

List<string> filters = new List<string>();

void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e) {
  this.BeginInvoke(new Action(() => {
    filters = new List<string>();
    foreach (var itemChecked in checkedListBox1.CheckedItems) {
      filters.Add("'" + itemChecked.ToString() + "'");
    }
    MessageBox.Show("Responible = " + string.Join(" OR ", filters.ToArray()));
  }));
}
Comments