Pieces
Pieces

Reputation: 2295

Iterate textboxes in order by name, inside a tab control

I have a bunch of textboxes, about 150 to be exact. They are inside different tabs of a tab control, and are not in order by name on screen. They are named simply textBox1, textBox2, textBox3... I would like to be able to iterate them in order by name and not by how they appear on the form. How would I got about doing this?

Upvotes: 3

Views: 510

Answers (1)

EgorBo
EgorBo

Reputation: 6142

public IEnumerable<Control> GetChildrenRecursive(Control parent)
{
    var controls = new List<Control>();
    foreach(Control child in parent.Controls)
        controls.AddRange(GetChildrenRecursive(child));
    controls.Add(parent); //fix
    return controls;
}

TextBox[] textboxes = GetChildrenRecursive(this)
       .OfType<TextBox>().OrderBy(i => i.Name).ToArray();

Upvotes: 5

Related Questions