Daniel
Daniel

Reputation: 2295

Is it possible to alter the order of Controls being looped through in WinForms

The following code loops through all controls in the current form and handles null values perfectly. My gripe with it is that it seems to follow the reserve of the tab order of the controls i.e. it starts with the last control and works it's way back to the first.

foreach (Control C in this.Controls)
{
    if (C.GetType() == typeof(System.Windows.Forms.TextBox))
    {
        if (C.Text == null || C.Text == string.Empty || C.Text == "")
        {
            setControlErrors(C, "This field cannot be empty, you must enter a value");
            return false;
        }
        else
        {
            errorProvider1.SetError(C, "");
        }
    }
    if (C.GetType() == typeof(System.Windows.Forms.ComboBox))
    {
        if(C.Text == null || C.Text == string.Empty || C.Text == "")
        {
            setControlErrors(C, "This field cannot be empty, you must select a value");
            return false;
        }
        else
        {
            errorProvider1.SetError(C, "");
        }
    }
}

How can I reverse this order easily? It seems weird to see validation errors in reverse order of the form layout. Changing the tab-index seems even worse than this.

Is there a better way to do this?

Upvotes: 0

Views: 643

Answers (3)

Dishonered
Dishonered

Reputation: 8831

You can sort the controls by tab index like this

foreach (Control control in this.Controls.Cast<Control>()
                                         .OrderBy(c => c.TabIndex))
{
    //..
}

Upvotes: 3

Advait Baxi
Advait Baxi

Reputation: 1628

You can achieve using following code

        var controls = this.Controls.Cast<Control>()
                           .OrderByDescending(x => x.TabIndex);

        foreach (var control in controls)
        {
        }

Upvotes: 1

Hix
Hix

Reputation: 39

How about this solution?

foreach (Control C in this.Controls.Cast<Control>().OrderBy(ctr => ctr.TabIndex))

Upvotes: 0

Related Questions