1

This code pre-filters a dataGridView so only the checked items in the list will be displayed.

The problem I'm facing is that the code somehow omits the very last item every time, unless I uncheck, check again and press "Go".

Here is a pic of the issue

This is my code:

public partial class Notifications : Form
{
    string filterstring = "";
    int count = 0;
    private void checkedListBox_ItemCheck(object sender, System.EventArgs e)
    {
        //  Loop through all items in the checkedBoxes.

        foreach (object itemChecked in checkedListBox.CheckedItems)
        {
            if (count != 0)
            {
                filterstring += "OR Responsible = '" + itemChecked.ToString() + "'";
            }
            else
                filterstring += "Responsible = '" + itemChecked.ToString() + "'";
            count += 1;
        }
    }
  private void button1_Click(object sender, EventArgs e)
    {
            DataTableCollection tables = myDatabaseDataSet.Tables;
            DataView view = new DataView(tables[0]);
            BindingSource source = new BindingSource();
            source.DataSource = view;
            dataGridView1.DataSource = source;
            source.Filter = filterstring;
    }

I know the solution might be silly but I can't figure it out.

1 Answers1

0
private void checkedListBox_ItemCheck(object sender, ItemCheckEventArgs e)
{
    if (e.NewValue == CheckState.Checked)
        filterstring = "Responsible = '" + checkedListBox.Items[e.Index].ToString() + "' OR";
    //  Loop through all items in the checkedBoxes.

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

You have to check new value of item is clicked. If it is checked you can include it in your filtering string. Also Removing last OR is much better than if in every iterator. Edit: Your event is EventArgs Bu it should be ItemCheckEventArgs

Hakan SONMEZ
  • 2,176
  • 2
  • 21
  • 32
  • The check state is not updated until after the ItemCheck event occurs.[Manage CheckedListBox ItemCheck event to run after an item checked not before](http://stackoverflow.com/a/32291665/3110834) – Reza Aghaei Oct 06 '16 at 01:08