Winform Preventing Controls Validated/Validating Event when setting focus on it programtically
You might have faced below kind of issues in your winform projects :
- You have added some validation on the Leave event of the text box control and at some point of action, you are getting those validation messages again and again which is making it in a dead lock and you have to restart the application by terminating it through task manager.
- The same issue as described above is also happening on some other events such as validated, validating etc of the control
There are lot of properties available to these controls which will make you to prevent such actions. The order of occurrence of the controls events in winform depends how the focus is being set to the controls. Suppose you are setting up the focus to a control by using TAB or SHIFT+TAB or other key in your keyboard or by calling the Select or SelectNextControl methods or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order:
- Enter
- GotFocus
- Leave
- Validating
- Validated
- LostFocus
and if your are changing the focus by using the mouse or by calling the Focus method of the control then focus events occur in the following order:
- Enter
- GotFocus
- LostFocus
- Leave
- Validating
- Validated
So while setting these property you need to keep in mind the order of the events.
So the most important thing which I wanted to discuss is to prevent validated/validating event fire on setting focus to the control.
Suppose you have placed a text box control on your form and you have written some logic to show some error message on its validated event based on some condition. When you will set focus of this control in some other action then this validated event will occur again and you will get the message again. So whenever you are setting the focus to this control having validated/validating event then first set the controls CausesValidation property to false and then set the Focus and then set CausesValidation property to true.
If the CausesValidation property is set to false, the Validating and Validated events are suppressed and it will prevent the control to fire these events again.
Important points to be remembered :
- If the CausesValidation property is set to false, the Validating and Validated events are suppressed.
- If the Cancel property of the CancelEventArgs is set to true in the Validating event delegate, all events that would usually occur after the Validating event are suppressed.
- Do not attempt to set focus from within the Enter, GotFocus, Leave, LostFocus, Validating, or Validated event handlers. Doing so can cause your application or the operating system to stop responding.
Comments
Post a Comment
Thanks for your valuable feedbacks.Keep visiting the blog...