Haseeb
Haseeb

Reputation: 990

How to find a control from controls of controls collection recursively?

My control "MyTextBox1" add dynamically on form1 under container1 control. This form1 can be child of form2 and form2 can be child of form3 and so on how can I find my control from multi controls collection?

e.g. MyTextBox1 exists in

form3.form2.form1.Container1.MyTextBox1

how to find my control by name from multi control collections?

I do not want to use recursive foreach control collection. I am looking for an smart/short code like controls.Find().

Upvotes: 0

Views: 904

Answers (1)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186668

If you don't want to put it recoursive, you can try BFS (Breadth First Search); let's implement it as an extension method:

public static class ControlExtensions { 
  public static IEnumerable<Control> RecoursiveControls(this Control parent) {
    if (null == parent)
      throw new ArgumentNullException(nameof(parent));

    Queue<Control> agenda = new Queue<Control>(parent.Controls.OfType<Control>());

    while (agenda.Any()) {
      yield return agenda.Peek();

      foreach (var item in agenda.Dequeue().Controls.OfType<Control>())
        agenda.Enqueue(item);
    }
  }
}

Then you can use it as

// Let's find Button "MyButton1" somewhere on MyForm 
// (not necessary directly, but may be on some container)
Button myBytton = MyForm
  .RecoursiveControls()
  .OfType<Button>()
  .FirstOrDefault(btn => btn.Name == "MyButton1");

Upvotes: 1

Related Questions