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);
}
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;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.