开发者

Iterates controls for checkboxes in C#

I want to go through all the check boxes in form.tab and mark them as not selected. I found this was the right decision:

     foreach (Control c in this.Controls)
     {
         CheckBox cb = c as CheckBox;
         if (cb! = null & & cb.Checked)
         {
            cb.Checke开发者_Go百科d = false;
         }
     }

But it does not work! And I do not understand why. I watched the debugger and cb is null. Why can this be? Where did I go wrong?


Probably, the CheckBoxes are contained in some container, therefore you have to do some recursive lookup or iterating directly over the Controls-collection of this container.


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.


I think the checkboxes controls are not in the form maybe they in other container like Group box or Panel

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜