简体   繁体   English

C# 复选框选中计数

[英]C# checkbox checked count

I have several checkboxes and a button inside a panel, that is inside a tabPage, inside a WinForm C# application.我在面板内有几个复选框和一个按钮,即在 tabPage 内,在 WinForm C# 应用程序内。

What I am trying to do is making sure at least one checkbox is checked so enable the button to be clickable, if not the button will be disabled (gray display non-clickable).我想要做的是确保至少选中一个复选框,以便使按钮可点击,否则按钮将被禁用(灰色显示不可点击)。

I tried this (in Form_Load event) but it didn't work:我试过这个(在Form_Load事件中)但它没有用:

int counter = 0;
        foreach (Control p in tabPage1.Controls)
        {
            if (p is Panel)
            {
                foreach (Control c in panel1.Controls)
                {
                    if (c is CheckBox)
                    {
                        if (((CheckBox)c).Checked)
                        {
                            counter++;
                        }
                        if (counter < 1)
                        {
                            button1.Enabled = false;
                        }
                        else
                        {
                            button1.Enabled = true;
                        }
                    }
                }
            }
        }

It's either because I am using the wrong event or the wrong place to put the code, or the code itself isn't correct, can anyone take a look please?要么是因为我使用了错误的事件或错误的代码放置位置,要么是代码本身不正确,有人可以看看吗?

You can do something like this (note.. your specific loops are redundant.. you know the name of the container.. why loop searching for it?)你可以做这样的事情(注意......你的特定循环是多余的......你知道容器的名称......为什么要循环搜索它?)

if (panel1.Controls.OfType<CheckBox>().Any(x => x.Checked)) {
    // at least one is checked..

This code should be run in two places:这段代码应该在两个地方运行:

  • The form's Load event, after you've loaded the checkboxes with any saved values加载带有任何已保存值的复选框后,表单的Load事件
  • The checkboxes' CheckedChanged event handlers, so the button state is updated as checkboxes are checked复选框的CheckedChanged事件处理程序,因此当复选框被选中时按钮状态会更新

Remove this part you never use "p" variable in your code below...删除这部分你永远不会在下面的代码中使用“p”变量......

foreach(Control p in tabPage1.Controls)
{
  if (p is Panel)
  {
int counter = 0;
foreach(Control c in panel1.Controls)
{
  if (c is CheckBox)
  {
    if (((CheckBox)c).Checked)
    {
      counter++;
    }
    if (counter < 1) {
      button1.Enabled = false;
    }
    else {
      button1.Enabled = true;
    }
  }
}

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

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