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?
+5
A:
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();
Nagg
2010-07-14 13:27:37
When I tried this there doesn't end up being anything in the textboxes array.
Pieces
2010-07-14 13:42:40
Oh, just saw your update, its strange though, it goes from textBox1 to textBox10 goes in order till the end then goes back to textBox2 up to textBox9...
Pieces
2010-07-14 13:46:27
Because its compared as a strings. You can use something like this: OrderBy(i => int.Parse(i.Name.Replace("textBox", ""))
Nagg
2010-07-14 13:51:34
I changed it to from an array to a list. Then am using the sort method on the names. Thanks a lot for your help.
Pieces
2010-07-14 13:54:01