1

I am using Foreach to loop all Controls within a win form. However, Foreach always arranges the Controls in alphabetical order.

I tried to set the tab index and also change the sequence of the Controls' code. However, the loop is still in alphabetical order.

Is there some methods for looping Controls in a winform with specific order?

1
  • Foreach does no such thing, the Controls collection is iterated in Z-order. Topmost control is first. You can change order with Bring to Front and Send to Back. Or use View + (Other Windows) + Document Outline and drag/drop to rearrange. Nov 29, 2011 at 7:14

2 Answers 2

4

Using the LINQ extension-method .OrderBy() (and companion .OrderByDescending()) you can use any ordering you want.

But because Controls is a non-generic collection, you need to convert it to a generic variant first. This can be done with either .OfType<T>() (filters) or .Cast<T>() (casts).

foreach (var c in Controls.OfType<Control>().OrderBy(c => c.Size.Top))
{
    // ...
}

If you need to modify the collection as you go, you can use .ToList() to make a snapshot.

foreach (var c in Controls.OfType<Control>().OrderBy(c => c.Size.Top).ToList())
{
    // ...
}

You will need to import the LINQ namespace to enable the extension-methods.

using System.Linq;
2
  • 1
    I could not find such method. :( BTW, I am using dotnet Framework 3.5.
    – SUT
    Nov 29, 2011 at 7:24
  • Ah, right. Controls is a non-generic IEnumerabe, not IEnumerable<T>. I updated the answer. Nov 29, 2011 at 7:40
0

foreach iterates trough the List of Controls. This lis ist "unsorted" and therefore you'll need to sort it.

If you need some specific sorting, i would copy the list to a Dictionary where the key is the Property you are sorting for.

Here a litte dummy code which sould explain what i meant.

Dictionary<int, IControl> controls = new Dictionary<int, IControl>();

foreach(IControl control in form.Controls){
    int tabIndex = control.TabIndex;
    controls.add(tabIndex, control);
}

controls.Sort();

foreach(IKeyValuePair<int, IControl> control controls){
    control.DoSome();
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.