Loop through all controls on asp.net webpage

后端 未结 7 1415
攒了一身酷
攒了一身酷 2020-12-01 22:17

I need to loop through all the controls in my asp.net webpage and do something to the control. In one instance I\'m making a giant string out of the page and emailing it to

7条回答
  •  时光取名叫无心
    2020-12-01 23:00

    Your original method will not work if you start from the root element of your document: something like page.Controls as you will only loop through the first level of controls, but remember a control can be composite. So you need recursion to pull that off.

            public void FindTheControls(List foundSofar, Control parent) 
            {
    
                foreach(var c in parent.Controls) 
                {
                      if(c is IControl) //Or whatever that is you checking for 
                      {
    
                          foundSofar.Add(c);
    
                          if(c.Controls.Count > 0) 
                          {
                                this.FindTheControls(foundSofar, c);
                          }
                      }
    
    
                }  
    
            }
    

提交回复
热议问题