0

I have a flowLayoutPanel that contains a lot of panels each of which contains two labels and a button. The label I need has a name starting with lbl_, other one is label. I need to change color of all labels with name lbl_. That is not a problem if all labels will change their color. I found that I can refer to any object of first layer using foreach cycle

    foreach(var label in this.Controls.OfType<Label>())
{
    label.BackgroundColor = Color.Black;
}

However, when I tried code below, it didn't work. So, now I ran out of ideas

foreach (var flowlayoutpanel in this.Controls.OfType<FlowLayoutPanel>())
        {
            foreach (var panel in flowlayoutpanel.Controls.OfType<Panel>())
            {
                foreach (var label in panel.Controls.OfType<Label>())
                {
                    MessageBox.Show("Test");
                }
            }
        }
Mauricio Gracia Gutierrez
  • 10,288
  • 6
  • 68
  • 99
  • 3
    What do you mean by "it didn't work?" – Terry Tyson Jul 09 '21 at 14:35
  • 3
    Have a look at my answer to [this question](https://stackoverflow.com/q/15186828/880990). The `ForAllControls` method extension loops all controls recursively. Also, I have made an [API Proposal: Add Descendants property for Control](https://github.com/dotnet/winforms/issues/5195) on github.com/dotnet/winforms for this. If you like it, please upvote it there. – Olivier Jacot-Descombes Jul 09 '21 at 14:36
  • Is this what you are looking for ? https://stackoverflow.com/questions/11992483/find-windows-forms-control-by-name-using-a-pattern – Mauricio Gracia Gutierrez Jul 09 '21 at 14:56
  • 1
    Build a UserControl and add a public method that allows to set whatever property of whatever child control to any value required. – Jimi Jul 09 '21 at 15:11
  • 1
    What happens?? Note: While you enumerate the controls you don't cast them, so you can only access properties that are present in [`Control`](https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control?view=net-5.0) – TaW Jul 09 '21 at 15:52
  • You are not performing a check to confirm the label name is "lbl_" as per your task description. – demoncrate Jul 15 '21 at 14:11

0 Answers0