为了账号安全,请及时绑定邮箱和手机立即绑定

如何选中/取消选中 GroupBox 中的所有复选框?

如何选中/取消选中 GroupBox 中的所有复选框?

C#
慕的地8271018 2022-12-24 10:45:09
我有一个包含多个 GroupBox 的表单。每个 GroupBox 内部都包含几个 CheckBox。每个 GroupBox 还具有(在其外部)两个关联的按钮,用于取消选中/选中链接的 GroupBox 内的所有复选框。我的计划是使用增强的 for 循环来遍历每个 GroupBox 内的所有 CheckBox。但是,GroupBoxes 缺少使循环工作所需的属性(getEnumerator?)。此外,我需要这样做,以便每次我手动选中或取消选中 CheckBox 时,TextBox 都会更新为存储在已选中 CheckBox 的标签属性上的值的总和。我发现了一些类似的问题,有人想选中/取消选中表单中的每个 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);}现在它完成了我想要它做的事情,但我仍然必须遍历所有组件才能找到 CheckBox。有没有更好的解决办法?
查看完整描述

2 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

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

}


查看完整回答
反对 回复 2022-12-24
?
绝地无双

TA贡献1946条经验 获得超4个赞

我认为这会奏效


foreach(CheckBox c in groupBox1.Controls.OfType<CheckBox>())

            {

                c.Checked = true;

            }


查看完整回答
反对 回复 2022-12-24
  • 2 回答
  • 0 关注
  • 220 浏览

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号