Scope Creep
Scope Creep

Reputation: 565

Winforms Control Validation Order

I have a winforms app that from a very high level displays a bunch of financial data in a datagridview where each column represents a week number of the year. The program gives the ability to right click a cell and copy its value to a range of cells in the grid.

Right clicking the source cell opens up a simple Form where the user can enter a start week and a stop week. Once the start/stop week inputs are validated, the parent form retrieves the values and uses them to copy the source value to the range of target cells.

The final validation check in my "Stop Week" validating event handler compares the start week value to the stop week value to make sure that the start week is less than the stop week. In order for this to work, I need the "Start Week" validating event to fire before the "Stop Week" validating event. As additional information, I am triggering validation with the following block of code

    Private Sub HandleOkButtonClick(sender As Object, e As EventArgs)
        If ValidateChildren(ValidationConstraints.Enabled) Then
            MessageBox.Show("Validation Passes")
            DialogResult = DialogResult.OK
            Close()
        Else 
            MessageBox.Show("Validation Fails")
        End If
    End Sub

When I first started working on this code however, the "Stop Week" validating event was firing first. What I found was that in the designer file, the "Stop Week" textbox was added to the forms control collection before the "Start Week" textbox. The only way I have been able to control the sequence of validating events is to change the order that controls are added to the Forms Controls collection in the designer. This seems like a sub optimal solution.

Is there a better way to control the sequence in which form controls validate?

Upvotes: 1

Views: 407

Answers (2)

Reza Aghaei
Reza Aghaei

Reputation: 125207

ValidateChildren internally uses a loop over Controls collection and validate the child controls in the same order which they appear in Controls collection.

To change the order of raising Validating event, you can use either of the following options:

  • At design-time, use Document Outline window to reorder the controls
  • At run-time, change the control index in the controls collection using Controls.SetChildIndex
  • Override ValidateChildren and implement your custom logic to raise the Validating events in a custom order (for example based on the TabOrder).

Upvotes: 2

Mary
Mary

Reputation: 15091

  1. You can set TabIndex in Properties window
For Each ctrl In Me.Controls.OfType(Of Control).OrderBy(Function(c) c.TabIndex)
  Debug.Print(ctrl.Name)
Next

Reorders for the duration of the For...Next

  1. You can also edit the order in Form1.Designer.vb where the controls are added to Controls collection. Risky business, I believe it gets overwritten at certain times.

Upvotes: 0

Related Questions