-1

The following piece of code gets all labels named "label_bluep"+i where i is between 1 and 5.

    for (int i = 1; i < 5; i++)
    {
        Label labelname = (Label)this.Controls.Find("label_bluep" + (i), false).FirstOrDefault();
        labelname.Parent = pictureBox_background;
    }

When the code runs, this works fine. If I called the Controls.Find() method again for the same object e.g copying and pasting that same code to get this:

    for (int i = 1; i < 5; i++)
    {
        Label labelname = (Label)this.Controls.Find("label_bluep" + (i), false).FirstOrDefault();
        labelname.Parent = pictureBox_background;
    }
    for (int i = 1; i < 5; i++)
    {
        Label labelname = (Label)this.Controls.Find("label_bluep" + (i), false).FirstOrDefault();
        labelname.Visible = true;
    }

I get the exception labelname was null.What's the reason for this?

tonyy
  • 27
  • 6
  • 6
    Is it because the label's parent is now the picture box and not `this` anymore? – Crowcoder Dec 13 '19 at 17:50
  • Does this answer your question? [Find control by name from Windows Forms controls](https://stackoverflow.com/questions/3898588/find-control-by-name-from-windows-forms-controls) – Trevor Dec 13 '19 at 17:51
  • @Crowcoder that does indeed seem to be the case. – tonyy Dec 13 '19 at 18:07

1 Answers1

2

The second parameter of ControlCollection.Find() tells if the controls of children of the current control should also be searched.

In the first loop you made all labels to children of pictureBox_background. So you need to use true to find the labels again:

Controls.Find("label_bluep" + i, true);

or to search only children of pictureBox_background:

pictureBox_background.Controls.Find("label_bluep" + i, false);
René Vogt
  • 43,056
  • 14
  • 77
  • 99