---
title: "Keep Focus back to the previous Textbox on failed validation"  
description: "Keep Focus back to the previous Textbox on failed validation"  
author: "Anonymous User"  
published: 2014-03-26  
updated: 2014-03-26  
canonical: https://www.mindstick.com/forum/1985/keep-focus-back-to-the-previous-textbox-on-failed-validation  
category: "c#"  
tags: ["c#"]  
reading_time: 1 minute  

---

# Keep Focus back to the previous Textbox on failed validation

I want [Focus](https://yourviews.mindstick.com/audio/1251/how-music-can-improve-your-focus-and-mood) back to the [previous](https://yourviews.mindstick.com/view/81421/unlock-2-0-is-just-like-previous-corona-lockdowns) Textbox if [validation](https://www.mindstick.com/articles/12234/validation-using-data-annotation-using-entity-framework) gets failed. I am validating the [Textbox control](https://www.mindstick.com/forum/155820/how-to-generate-textbox-control-using-htmlhelper-in-razor-view) [value](https://www.mindstick.com/articles/23219/an-optimized-description-adds-value-to-experience-and-in-turn-effectively-guest-posting-packages) on lostFocus event. \
Need some help.

## Replies

### Reply by Pravesh Singh

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)


---

Original Source: https://www.mindstick.com/forum/1985/keep-focus-back-to-the-previous-textbox-on-failed-validation

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
