简体   繁体   中英

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?

eg 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().

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM