How to get all buttons and labels under splitContainer.Panel2

3.2k views Asked by At

I want to get the background color of all buttons and labels under splitContainer.Panel2. When I try it I discover I not success to run on any control (under Panel2) I try this code:

foreach (Control c in ((Control)splitContainer.Panel2).Controls)
{
    if ((c is Button) || (c is Label))
        MessageBox.Show("Name: " + c.Name + "  Back Color: " + c.BackColor);
}

How can I get all background colors of all labels and buttons under splitContainer.Panel2 ?

EDIT:

  1. I have some panels in splitcontainer.Panel2 and the buttons and labels are in the panels.
  2. I get only this meesage: "Name: panel_Right Back Color: Color [Transparent]"
3

There are 3 answers

0
No Idea For Name On BEST ANSWER

you get the message probably because you have a panel under your splitContainer.Panel2 and should do:

foreach (Control c in ((Control)splitContainer.Panel2).Controls)
{
    if(c is Panel)
    {
      foreach (Control curr in c.Controls)
      {
         MessageBox.Show("Name: " + curr.Name + "  Back Color: " + curr.BackColor);
      }
    }
}
1
Shaharyar On

You should also add a check for Button and Label. Add this line before messagebox:

if ((c is Button) || (c is Label))
0
King King On

You can do this without LINQ, but I want to use LINQ here:

public IEnumerable<Control> GetControls(Control c){            
  return new []{c}.Concat(c.Controls.OfType<Control>()
                                    .SelectMany(x => GetControls(x)));
}    
foreach(Control c in GetControls(splitContainer.Panel2).Where(x=>x is Label || x is Button))
   MessageBox.Show("Name: " + c.Name + "  Back Color: " + c.BackColor);