System.StackOverflowException on TextBox.Focus() RRS feed

  • Question

  • Hi All.

    I stack on problem. In my C# code when I validating field I would like return cursor back. For that I'm using TextBox.Focus(). But exactly that line give me error System.StackOverflowException. How to fix the problem?


    Sunday, April 12, 2020 3:40 PM

All replies

  • The Stack Overflow Exception typically occurs when you have an infinite recursion. This means the a subroutine calls itself, and then calls itself, and then calls itself... until there's no more space in the stack and then an exception is thrown. It can also be an indirect recursion, such as a routine A that calls B and then B calss A and then A calss B...

    This could easily happen if you validate a textbox when it loses focus, and you do this in more than one textbox. When you use Focus() to give focus to a different textbox, the validation for the taxtbox that los focus is triggered, so it focuses the control, so the other control loses focus, so its validation triggers, so it changes focus again, and so on and so on.

    There's no way to determine where exactly this problem is happening without examining the code, and sometimes the code is so complex that it is untractable and a simple examination does not reveal the problem. In such cases you use the debugger along with breakpoints to follow the execution of the program and determine what exactly is executing and when.

    To fix it, you need to add something in the code to stop the recursion. This will typically be an "if" that checks a variable that does "something" to tell when to recurse or not recurse. Exactly where to set and reset the variable or use it in an "if" can't be said beforehand without a careful examination fo the problem at hand.

    Sunday, April 12, 2020 4:20 PM
  • Is this related to your WPF question concerning validating an email address? Did you see my reply?

    Please remember to mark the replies as answers if they help and unmarked them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.

    NuGet BaseConnectionLibrary for database connections.

    profile for Karen Payne on Stack Exchange

    Monday, April 13, 2020 12:46 AM