简体   繁体   English

迭代C#中复选框的控件

[英]Iterates controls for checkboxes in C#

I want to go through all the check boxes in form.tab and mark them as not selected. 我想浏览form.tab中的所有复选框,并将其标记为未选中。 I found this was the right decision: 我发现这是正确的决定:

     foreach (Control c in this.Controls)
     {
         CheckBox cb = c as CheckBox;
         if (cb! = null & & cb.Checked)
         {
            cb.Checked = false;
         }
     }

But it does not work! 但这行不通! And I do not understand why. 而且我不明白为什么。 I watched the debugger and cb is null . 我看着调试器, cbnull Why can this be? 为什么会这样呢? Where did I go wrong? 我哪里做错了?

CheckBox可能包含在某个容器中,因此您必须进行一些递归查找或直接在此容器的Controls集合上进行迭代。

private void FindControls(Control Page)
{
     foreach (Control ctrl in this.Controls)
     {
          if (ctrl is CheckBox)
          {
              if (cb! = null & & cb.Checked)
              {                   
                   cb.Checked = false;                
              }
          }
          else 
          {
              if (ctrl.Controls.Count > 0)
              {
                   FindControls(ctrl);
              }
          }
     }
}

Try changing the first line from: 尝试从以下位置更改第一行:

this.Controls

to

this.tab.Controls

Your current code is looping though the controls directly on the form. 您当前的代码通过控件直接在窗体上循环。 You need to loop through the controls on the tab. 您需要遍历选项卡上的控件。

我认为复选框控件的形式可能不是它们在其他容器中,例如“组”框或“面板”

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

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