BigBlackBunny
BigBlackBunny

Reputation: 77

Checking and Unchecking a list of CheckBoxes

I have been able to check all the boxes in the list using the checkAll (a checkbox), but can't seem to uncheck them.

In the foreach, when I put in "industry.Checked = true", it checks all of them just fine. I want to also be able to uncheck them all, by unchecking the checkAll box.

    private void checkAll_CheckedChanged(object sender, EventArgs e)
    {
        List<CheckBox> industries = new List<CheckBox>();
        industries.Add(checkBasicIndustries);
        industries.Add(checkCapitalGoods);
        industries.Add(checkConsumerDurables);
        industries.Add(checkConsumerNonDur);
        industries.Add(checkConsumerServices);
        industries.Add(checkEnergy);
        industries.Add(checkFinance);
        industries.Add(checkHealthcare);
        industries.Add(checkMiscellaneous);
        industries.Add(checkPublicUtilities);
        industries.Add(checkTechnology);
        industries.Add(checkTransportation);

        foreach (CheckBox industry in industries)
        {
            if (industry.Checked = false)
            {
                industry.Checked = true;
            }

            else { industry.Checked = false; }

        }
    }

Upvotes: 0

Views: 87

Answers (1)

Steve
Steve

Reputation: 216243

Typo in

if (industry.Checked = false)    // Assignment operator

The single = assigns the value false to the Checked property.
So you set always all your CheckBoxes to false.

It should be

if (industry.Checked == false)   // Comparison operator

or just

if (!industry.Checked)

But better of all is (as suggested below by Matthew Mcveigh)

foreach (CheckBox industry in industries)
    industry.Checked = !industry.Checked;

reducing your code to a single line

Upvotes: 2

Related Questions