tags:

views:

74

answers:

2

Given a control that has child controls. How do you give focus to the child control that has the lowest tabindex without looping through all the controls?

+1  A: 

I will do it by looping through the controls, there is nothing wrong with that. That is probably the simplest solution.

Ricardo
+1  A: 

This solution doesn't have the performance you are looking for, but it's the "easy way." There may be an "easier way" that I am ignorant of.

var firstControl = this.AllChildControls().OrderBy(m => m.TabIndex).First();
firstControl.Focus();

The code snippet is dependant on the following extension method.

/// <summary>
/// Preforms a preorder iteration through all children of this control, recursively.
/// </summary>
/// <returns></returns>
public static IEnumerable<Control> AllChildControls(this Control control)
{
   foreach (Control child in control.Controls)
   {
        yield return child;
        foreach (var grandchild in child.AllChildControls())
            yield return grandchild;
    }
}
Stuart Branham
As I said, you still have to loop through all the controls...
Ricardo
I don't need recursive searches in this case. This will work.Dim xcon = (From item In Me.Controls.Cast(Of Control)() Where item.TabStop = True Order By item.TabIndex Select item).First
devSpeed