Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I evaluate two groups of items with a foreach loop in C# winforms?

I have a winforms TabControl and I am trying to cycle through all the controls contained in each tab. Is there a way to add and in a foreach loop or isn't it possible to evaluate more than one group of items? For example this is what I'd like to do:

foreach (Control c in tb_Invoices.Controls and tb_Statements.Controls)
{
    //do something
}

OR

foreach (Control c in tb_Invoices.Controls, tb_Statements.Controls)
{
    //do something
}

Is this possible, and if not, what is the next best thing? Do I need to use a for loop?

like image 690
gnarlybracket Avatar asked Aug 07 '13 13:08

gnarlybracket


2 Answers

foreach(TabPage page in yourTabControl.TabPages){
   foreach(Control c in page.Controls){
      LoopThroughControls(c);
   }  
}

private void LoopThroughControls(Control parent){
   foreach(Control c in parent.Controls)
      LoopThroughControls(c);
}
like image 174
King King Avatar answered Oct 19 '22 20:10

King King


Final solution:

var allControls = from TabPage p in tabControl.TabPages
                  from Control c in p.Controls
                  select c;

Original answer - use Concat:

var allControls = tb_Invoices.Controls.Cast<Control>()
                             .Concat(tb_Statements.Controls.Cast<Control>();

BTW I think it's better to use simple non-generic ArrayList here

ArrayList allControls = new ArrayList();
allControls.AddRange(tb_Invoices.Controls);
allControls.AddRange(tb_Statements.Controls);
like image 27
Sergey Berezovskiy Avatar answered Oct 19 '22 21:10

Sergey Berezovskiy