views:

40

answers:

2

Hi All, I'm opening a modal dialog asking the user to fill certain fields.

if(dlgUserDetail.ShowDialog() == DialogResult.OK)
{ 

}

On click of OK, the control comes to the parent form where I'm validating the user input.

If the validation fails, I wanted to keep the dialog to be open with the old values. Since it is modal dialog, the form gets closed.

It seems to be a common problem as I see many discussion on net, but nowhere I was able to find a solution.

Please let me know how to solve this problem. Thanks.

Regards ArunDhaJ

+1  A: 

One solution is to put validate logic into dlgUserDetail form and invoke it on OnClosing event. If the validation failed then prevent the form from closing.

Arseny
+1  A: 

If it is your dialog you could add a CancelEventArgs event called Validate or InputOk (similar to FileOk in OpenFileDialog) and have your main form check the input in a method. Before calling DialogResult = DialogResult.OK in your dialog, you add a ´onValidate` call to check if the input is valid.

{
    // dialog
    {
        if (onValidate()) {
            DialogResult = DialogResult.OK;
        }
    }

    private bool onValidate() {
       CancelEventHandler handler = Validate;
       if (handler == null) {
           return true;
       }
       CancelEventArgs args = new CancelEventArgs();
       handler(this, args);
       return args.Cancel;
    }
}

{
    // form
    {
        dlgUserDetail.Validate += valid;
        if(dlgUserDetail.ShowDialog() == DialogResult.OK) { }
    }

    private void valid(object sender, CancelEventArgs e) {
        // check input and set
        e.Cancel = true;
        // if not valid
    }
}
Patrick
This worked like a charm. Thanks a lot for your suggestion. :)
ArunDhaJ
@ArunDhaJ: np. Just remember to only subscribe to the event once, or you will validate the code several times over, which is somewhat of a performance killer. :-)
Patrick
Yep, u r right. I'll add unsubscription too.
ArunDhaJ