简体   繁体   中英

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+ "%";

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() + "%";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM