Foreach over multiple ControlCollections

I have a tab control in my Windows Form, and I want to iterate over each element in two different tabs. When the file opens, I want all the elements of both to be included, and when the file is closed, all should be disabled.

I do not know how to do this, however, since the controls are not in the array or list, but in the ControlsCollection. I asked about foreach statements a second time and found out a little about lambda, but I don't know how I can apply it here.

Here is what I have:

List<Control.ControlCollection> panels = new List<Control.ControlCollection>(); panels.Add(superTabControlPanel1.Controls); panels.Add(superTabControlPanel2.Controls); foreach(Control.ControlCollection ctrlc in panels){ foreach (Control ctrl in ctrlc) { } } 

Is this possible with a single foreach clause, or is it somehow simpler?

+4
source share
4 answers

I would use Linq with the following:

 foreach (var ctrl in panels.SelectMany (x => x.Cast<Control> ())) { // Work with the control. } 

The key is to use the Cast extension method in IEnumerable to make it usable with SelectMany.

+4
source

Did you know that if you disable the parent control, all nested controls are also disabled? Simply disabling the two tab bars will also disable all children. Turning on the panel returns the effect.

I know this does not answer your question, but it is the best solution.

+1
source

I would do something like this:

 List<Control> controls = new List<Control>(); controls.AddRange(superTabControlPanel1.Controls.GetControls()); controls.AddRange(superTabControlPanel2.Controls.GetControls()); foreach(Control ctrl in controls){ //Do something } 

At the moment, I don't have VS, and I'm not sure if GetControls () exists. But you can use the general idea: instead of collecting panels, have a set of controls and iterate over the controls in a single loop.

0
source

I would probably combine the two collections and not use a common List<T> all together.

 var controls = superTabControlPanel1.Controls.Union(superTabControlPanel2.Controls); foreach (var control in controls) { //... } 

Or you can combine several collections together.

 var controls = (superTabControlPanel1.Controls) .Union (superTabControlPanel2.Controls) .Union (superTabControlPanel3.Controls); 
0
source

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


All Articles