Alex Kibler
Alex Kibler

Reputation: 4954

On leaving a control, how can I give that control focus again?

I've got TextBoxes in a C# form. The user enters data, and then when they leave the control (almost always by hitting Tab), I check the data to make sure it's valid. If it is invalid, I want to highlight their text so they can immediately fix it rather than having to click it.

Right now, on Control.Leave, I validate their entry. This works just fine. However, since they hit Tab, right after they dismiss the error message, it goes on to the next object, even though I've got ((TextBox)sender).Focus();

How can I have the above line fire after the form Tabs to the next control.

Upvotes: 0

Views: 1423

Answers (3)

user1112560
user1112560

Reputation: 185

If you handle the Control.Validating event, setting e.Cancel to true will stop the change of focus from occurring.

Note that this method will also stop buttons from working, so you may need to set Control.CausesValidation to false on certain buttons.

You will also need the following snippet on the main form to allow the close button to work:

protected override void OnFormClosing(FormClosingEventArgs e) {
    e.Cancel = false;
    base.OnFormClosing(e);
}

Upvotes: 1

Michael Di Felice
Michael Di Felice

Reputation: 406

You may want to look into Control.CausesValidation property

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.causesvalidation(v=vs.110).aspx

You can validate the control prior to the user leaving focus rather than waiting on Focus moving itself.

And here's MSDN documentation for Control.Validating event, does a good job at laying out the sequence of events when gaining / losing focus of a Control.

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.validating(v=vs.110).aspx

Notice how Control.Validating and Control.Validated are launched prior to Control.LostFocus. You can perform your validation step prior to allowing the user to lose focus of your Textbox.

There's also a pretty good previous answer on stackoverflow.com which outlines how to do this: C# Validating input for textbox on winforms

Upvotes: 1

krisdyson
krisdyson

Reputation: 3255

Try using the LostFocus event on the TextBox to Focus it again

Upvotes: 0

Related Questions