KEEP FOCUS BACK TO THE PREVIOUS TEXTBOX ON FAILED VALIDATION

Ankit Singh

Total Post:341

Points:2389
Posted by  Ankit Singh
C# 
C#
 1136  View(s)
Ratings:
Rate this:
I want Focus back to the previous Textbox if validation gets failed. I am validating the Textbox control value on lostFocus event. 

Need some help.
  1. Pravesh Singh

    Post:412

    Points:2888
    Re: Keep Focus back to the previous Textbox on failed validation

    Hi Ankit,

    If you attempt to focus an element inside its own LostFocus handler you will face a StackOverflowException, I'm not sure about the root cause (I suspect the focus kind of bounces around) but there is an easy workaround: dispatch it.

    private void TextBox_LostFocus(object sender, RoutedEventArgs e)

    {

        var element = (sender as TextBox);

        if (!theTextBoxWasValidated())

        {

            // doing this would cause a StackOverflowException

            // element.Focus();

            var restoreFocus = (System.Threading.ThreadStart)delegate { element.Focus(); };

            Dispatcher.BeginInvoke(restoreFocus);

        }

    }

    Through Dispatcher.BeginInvoke you make sure that restoring the focus doesn't get in the way of the in-progress loss of focus (and avoid the nasty exception you'd face otherwise)

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!