Validating does not work as it should

G

Guest

Usage:
I have a dialog box, with default button with DialogResult.OK, cancel button
with DialogResult.Cancel, and a few dynamically added usercontrols.
In these usercontrol, there is another usercontrol with a textbox, that
required specific text to be entered.
On TextBox.Validating(.....), I set e.Cancel = True, to stop leaving
textbox, for some reasons.
Problem:
Clicking Cancel button closes form, thats ok. OK button is not clickable if
textbox is validated with e.Cancel=True. But if I press ENTER, OK button is
executed, and a form is closed. Validating event is fired, but it does
nothing to prevent form closing.
Question:
How to implement correct validation, and prevent form closing while
remaining DefaultButton functionality (all validation must be done in some
child control)?
 
B

Bruce Wood

First off, I agree with you that validation seems broken in this case.
I would expect that pressing Enter would do exactly the same thing as
clicking the OK button.

That said, you still need to validate when the user presses OK, as well
as in the text box's Validating method. What if the user never enters
the text box and so never triggers the Validating event handler? The
initial contents of the text box as loaded may be invalid, and you
should be checking all of your controls when the user clicks OK.

I solved this problem by separating my validation from my Validating
events. I coded my validation logic for each control into a private
method. In the control's Validating event handler I call that control's
validation method. Then, in the OK button's Click event handler, I call
all of the validation methods in sequence and light up ErrorProvider
icons on all of the fields that have problems. Only if all validation
methods pass validation do I accept the input and close the form.
 
G

Guest

I solved it by removing default button, and added custom filtering on KeyDown
event
if e.Keydata = Enter then if btnOk.Focus then btnOk.PerformClick

As I said that textbox is just added dynamically at runtime. Some kind of
extension. It's value is allways correct, it only has to stop leaving until
either it is cleared or correct.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top