如何检查/取消选中GroupBox中的所有CheckBox?

问题描述 投票:0回答:2

我有一个包含多个GroupBox的表单。每个GroupBox里面都包含几个CheckBox。每个GroupBox还有(在它之外)两个相关的按钮,取消选中/检查链接的GroupBox中的所有CheckBox。

我的计划是使用增强的for循环来遍历每个GroupBox中的所有CheckBox。但是,GroupBoxes缺少使循环工作所需的属性(getEnumerator?)。

另外,我需要这样做,每次我手动检查或取消选中CheckBox时,TextBox都会获得更新,其中包含存储在已检查CheckBox的tag属性上的值的总和。

我发现了一些类似的问题,人们希望检查/取消选中表单中的每个CheckBox。这是适合我的应用程序的代码。

private void CalculateComplementPrice()
{
    try
    {
        double total = 0;
        foreach (Control c in Controls) //I don't want to iterate through all the form
        {
            if (c is CheckBox)
            {
                CheckBox cb = (CheckBox)c;
                if(cb.Checked == true)
                {
                    total += Convert.ToDouble(cb.Tag);
                }
            }
        }
        tbComplementsPrice.Text = Convert.ToString(total);
    }
    catch
    {
        MessageBox.Show("Error on the complement GroupBox", "Error", MessageBoxButtons.OK);
    }
}

有没有办法遍历GroupBox的所有组件而不必遍历所有表单?

== ==更新

我改变了之前发现的一些代码:

private void CalculateComplementPrice()
{
    double total = 0;
    try
    {
        foreach (Control ctrl in this.Controls)
        {
            if (ctrl.ToString().StartsWith("System.Windows.Forms.GroupBox"))
            {
                foreach (Control c in ctrl.Controls)
                {
                    if (c is CheckBox)
                    {
                        if (((CheckBox)c).Checked == true)
                        {
                            total += Convert.ToDouble(c.Tag);
                        }
                    }
                }
            }
        }
    tbComplementPrice.Text = string.Format("{0:F2}", total);
}
catch
{
    MessageBox.Show("Error calculating the complement price", "Error", MessageBoxButtons.OK);
}

现在它做我想做的事情,但我仍然需要迭代所有组件才能找到CheckBoxes。有没有更好的解决方案?

c# winforms
2个回答
2
投票
double total = 0;
try
{
    foreach (GroupBox ctrl in this.Controls.OfType<GroupBox>()) //We get all of groupboxes that is in our form (We want the checkboxes which are only in a groupbox.Not all of the checkboxes in the form.)
    {
        foreach (CheckBox c in ctrl.Controls.OfType<CheckBox>()) //We get all of checkboxes which are in a groupbox.One by one.
        {
            if (c.Checked == true)
            {
                total += Convert.ToDouble(c.Tag);
            }
        }
    }
    tbComplementPrice.Text = string.Format("{0:F2}", total);
}
catch
{
    MessageBox.Show("Error calculating the complement price", "Error", MessageBoxButtons.OK);
}

0
投票

我认为这会奏效

foreach(CheckBox c in groupBox1.Controls.OfType<CheckBox>())
            {
                c.Checked = true;
            }
© www.soinside.com 2019 - 2024. All rights reserved.