Ali
Ali

Reputation: 3469

How to find the First Control in Tab Order in a Control?

I write an Extension method to get the First Control in Tab Order in a Control as below:

public static void FirstControlFocus(this Control ctl)
{
    ctl.Controls.OfType<Control>().Where(c => c.TabIndex == 0).FirstOrDefault().Focus();
}

The problem is sometimes the maybe there is no existing control with TabOrder==0!(for example developer delete the control with Taborder==0 in design mode) and this lead to error in runtime.

I handle this problem with this code:

public static void FirstControlFocus(this Control ctl)
{
    if (ctl.Controls.OfType<Control>().Any(c => c.TabIndex == 0))
        ctl.Controls.OfType<Control>().Where(c => c.TabIndex == 0).FirstOrDefault().Focus();
    else if (ctl.Controls.OfType<Control>().Any(c => c.TabIndex == 1))
        ctl.Controls.OfType<Control>().Where(c => c.TabIndex == 1).FirstOrDefault().Focus();
    else if (ctl.Controls.OfType<Control>().Any(c => c.TabIndex == 2))
        ctl.Controls.OfType<Control>().Where(c => c.TabIndex == 2).FirstOrDefault().Focus();
    else if (ctl.Controls.OfType<Control>().Any(c => c.TabIndex == 3))
        ctl.Controls.OfType<Control>().Where(c => c.TabIndex == 3).FirstOrDefault().Focus();
}

But I think it's not the best way, Could anyone suggest a better way to handle this problem? Thanks in advance.

Upvotes: 2

Views: 611

Answers (1)

Roman
Roman

Reputation: 12171

You can use Min():

public static void FirstControlFocus(this Control ctl)
{
    ctl.Controls.OfType<Control>()
       .FirstOrDefault(c => c.TabIndex == ctl.Controls.OfType<Control>().Min(t => t.TabIndex))
      ?.Focus();
}

There is no need in Where() - you can use FirstOrDefault() only. Also, consider using ?.Focus() in case if FirstOrDefault() returns null.

Upvotes: 2

Related Questions