Search code examples
c#visual-studiotextboxtextchanged

How to append a String to a text in TextBox using TextChanged event?


I have a TextBox named PercentageText and I have to append "%" to text in the TextBox using TextChanged event. but it allows me to type only one character,at the moment I type the second Character, it Throws an Exception Called System.StackOverflowException. here is my code inside TextChanged event block.

PercentageText.Text = PercentageText.Text.Trim() + "%";

I tried the following code as well

PercentageText.Text = PercentageText.Text+ "%";

Solution

  • The problem is that you are amending the Text of your control inside the TextChange event, which then changes the text and fires the event again.

    So you get caught in an unending loop and eventually a stackoverflow exception is thrown.

    So you need to indicate some way of only running the code in your method once. A simple way is to use a boolean value to indicate if you are handling it or not. Like this

    //Defined in your class
    private bool skipTextChange = false;
    
    
    //Amend the TextChange event
    if (skipTextChange )
        skipTextChange = false;
    else
    {
        skipTextChange = true;
        PercentageText.Text = PercentageText.Text.Trim() + "%";
    }