Search code examples
c#listviewcheckboxtabcontrollistviewitem

Loop through several ListViews (in a TabControl) and clearing checkboxes c#


This is driving me nuts! I have a TabControl wich holds 5 tabs. Each tab has a ListView with multiple checkboxes. Now i'd like to pass my TabControl to a method and for each ListView - clear all checkboxes.

Doesn't seem so hard, but it was!

foreach (var myItem in tabControl1.Controls) {
    if (myItem is ListView) { // surprisingly doesnt work...
        // loop through ListView find CheckBox...
    }
}

What is wrong with the if-statement?

Edit: This code works! Hmm?!

foreach (ListViewItem listItem in listView1.Items)
{
    listItem.Checked = false;
} 

Solution: I Was looking for "CheckBox", but it's actually a ListViewItem with the property Checked = true/false.

Also see code below, nice recursive method!


Solution

  • Recursively:

    void ClearAllCheckBoxes(Control ctrl)
    {
        foreach (Control childControl in ctrl.Controls)
            if (childControl is ListView)
                foreach (ListViewItem item in ((ListView)childControl).Items)
                    item.Checked = false;
            else ClearAllCheckBoxes(childControl);
    }
    

    And use:

    ClearAllCheckBoxes(tabControl1);