What is the difference between the LostFocus
and the Leave
events of TextBox
?
The LostFocus event occurs after the Exit event. If you move the focus to a control on a form, and that control doesn't have the focus on that form, the Exit and LostFocus events for the control that does have the focus on the form occur before the Enter and GotFocus events for the control you moved to.
Definition and Usage The onblur event occurs when an object loses focus. The onblur event is most often used with form validation code (e.g. when the user leaves a form field).
Net. A very useful event you can use for text boxes is the Leave event. It allows you to validate a text box when a user tries to leave it. You can check, for example, if the text box is blank.
Check the notes section on these links:
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.lostfocus.aspx
http://msdn.microsoft.com/en-us/library/system.windows.forms.control.leave.aspx
According to MSDN, there is difference when changing focus of a control. The Leave
event occurs before a validation and LostFocus
occurs after validation.
I see that I'm still getting views and upvotes on the answer that I posted couple of years ago. It has now become imperative that I include a (rather important) quote from the MSDN links above to avoid confusion among new programmers (note the difference of order esp. in case of focus by using the mouse or by calling the Focus
method):
When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), 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 <--- before validation Validating -- |<--- validation Validated -- LostFocus <--- after validation
When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:
Enter GotFocus LostFocus <--- before validation Leave <--- before validation Validating -- |<--- validation Validated --
N.B: Emphasis on text and indicators in the quote added by me
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With