Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference Between LostFocus Event and Leave Event of TextBox

Tags:

c#-4.0

What is the difference between the LostFocus and the Leave events of TextBox?

like image 966
CoronaVirus Avatar asked Oct 12 '12 06:10

CoronaVirus


People also ask

What is LostFocus event?

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.

Which event occurs when the focus leaves a control?

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).

What is leave event in C#?

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.


1 Answers

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.


UPDATE: 14 Feb 2019

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

like image 144
Fr0zenFyr Avatar answered Sep 28 '22 08:09

Fr0zenFyr