Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting number of current checked boxes and output that number in c#

Tags:

c#

checkbox

I am trying to count the number of the current checked "checked box" in a group box. I have like 10 check boxes.

I been trying some code but I only managed to count upward if I checked the box but not the other way around. So it is only adding up (but not +1 each time).

So what approach do I have to take to count the number of the current (not incrementing) checked boxes? Thank you

int checkedBoxes = 0;

private void checkBox1_Click(object sender, EventArgs e)
{
    CheckBox check = (CheckBox)sender;
    bool result = check.Checked;

    if (result == true)
    {
        btnDone.Enabled = true;
    }

    foreach (Control c in grpToppings.Controls)
    {
        CheckBox cb = c as CheckBox;
        if (cb != null && cb.Checked)
        {
            checkedBoxes += 1;
            int how_many = checkedBoxes;
        }
    }
}

private void btnDone_Click(object sender, EventArgs e)
{
    string name = textbox_orderName.Text;
    MessageBox.Show("\nhow many: " + checkedBoxes, "It is done",
    MessageBoxButtons.OK);
}
like image 678
lufee Avatar asked Dec 31 '25 15:12

lufee


1 Answers

Just move the assignment of checkedBoxes in the event checkBox1_Click as you are looping over all the child controls again and count should be reset.

int checkedBoxes;

private void checkBox1_Click(object sender, EventArgs e)
{
    checkedBoxes = 0;
    CheckBox check = (CheckBox)sender;
    bool result = check.Checked;

    if (result == true)
    {
        btnDone.Enabled = true;
    }

    foreach (Control c in grpToppings.Controls)
    {
        CheckBox cb = c as CheckBox;
        if (cb != null && cb.Checked)
        {
            checkedBoxes += 1;
            int how_many = checkedBoxes;
        }
    }
}
like image 94
Richa Garg Avatar answered Jan 05 '26 05:01

Richa Garg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!