Wednesday, October 13, 2010

Validate all the controls of a form in one step in c#

What I was trying to achieve was the following: I created a dialog with some options being entered in textboxes. The textboxes values are validaded using there respective "validated" event. And the user validate the dialog in two possible way: 1 using the "OK" button or, 2 using the "enter" key shortcut.

When implementing the "Enter" key shortcut to validate the entire dialog and close it, the last textbox do not lost focus and therefor do not trigger is validate event, which is annoying.

The solution is to trigger the validate event for all form's children at once before closing the dialog, using the " this.ValidateChildren()" command. Then the "OK" button event is also artificially triggered:

 private void MyControl_KeyDown(object sender, KeyEventArgs e)
        {
            EventArgs eee = new EventArgs();
            switch (e.KeyCode)
            {
                case Keys.Enter: //opens the Options
                    this.ValidateChildren();
                    OkButton_Click(OkButton, eee);
                    break;
            }
        }

 P.S. Do not forgot to set the "KeyPreview" parameter of your form to "true"  :

No comments:

Post a Comment