Foreach Control ctrl in SomePanel.Controls does not get all controls

I have a panel with a bunch of shortcuts and text fields inside it.

The code:

foreach (Control ctrl in this.pnlSolutions.Controls) 

It seems that you just need to find the html table inside the panel and two letters. But it does not get the text fields that are in the html table. Is there an easy way to get all the controls inside the panel regardless of nesting ?

thanks!

+4
source share
5 answers

Here's the lazy solution:

 public IEnumerable<Control> GetAllControls(Control root) { foreach (Control control in root.Controls) { foreach (Control child in GetAllControls(control)) { yield return child; } } yield return root; } 

Remember also that some controls store an internal set of elements (for example, ToolStrip), and this will not list them.

+8
source

You will need to hook it recursively through the controls, think of it as going through the folder structure.

there is a sample here

+4
source

As far as I know, you need to implement recursion yourself, but it is not difficult.

Sketch (untested):

 void AllControls(Control root, List<Control> accumulator) { accumulator.Add(root); foreach(Control ctrl in root.Controls) { AllControls(ctrl, accumulator); } } 
+2
source

I had exactly the problem indicated in the question, so this might help someone. I tried to clear the control collection before overwriting it.

 private void clearCollection(Control.ControlCollection target) { foreach (Control Actrl in target) { if (Actrl is Label || Actrl is Button) { target.Remove(Actrl); } } } 

Having deleted the control inside the foreach loop, it should fiddle with internal pointers, and the result is that the controls in the collection are skipped. My solution was to find all the controls and then delete in a separate loop.

 private void clearCollection(Control.ControlCollection target) { List<Control> accumulator = new List<Control>(); foreach (Control Actrl in target) { if (Actrl is Label || Actrl is Button) { accumulator.Add(Actrl); // find all controls first. } } for (int i = 0; i < accumulator.Count; i++) { target.Remove(accumulator[i]); } } 
+2
source

The reason is that the only controls that are direct children of your panel are the table and literals that you mention, and only they return this.pnlSolutions.Controls .

Shortcut text fields are child table controls, which makes them grandchildren of the panel.

As @Yoda points out, you need to go through the controls recursively to find them all.

+1
source

Source: https://habr.com/ru/post/1309683/


All Articles