简体   繁体   English

计算当前复选框的数量并在c#中输出该数字

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

I am trying to count the number of the current checked "checked box" in a group box. 我试图计算组框中当前选中的“复选框”的数量。 I have like 10 check boxes. 我有10个复选框。

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). 所以它只是加起来(但不是每次+1)。

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. 只需在事件checkBox1_Click移动checkedBoxes的赋值,因为您再次循环遍历所有子控件并应重置count。

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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM