P.C P.C - 2 months ago 6
C# Question

C# Last Item of the checkedListBox is not showing up

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.

Answer
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