Search code examples
c#textboxtextchanged

First Character goes to the end of the text when I type in TextBox


I have a TextBoxnamed PercentageText. I used TextChanged event to Append "%" to text typed inside the TextBox. The code inside the TextChanged event is given below

if (skipTextChange)
                skipTextChange = false;
            else
            {
                skipTextChange = true;
                if (PercentageText.Text =="")
                {
                    PercentageText.Text = " ";
                }

                if (PercentageText.TextLength == 1)
                {
                    if (PercentageText.Text != "%")
                    {
                        PercentageText.Text =""+ PercentageText.Text.Trim() + "%";
                    }
                }
            }

and initiallized SkipTextChange=false; out side the TextChanged Event Block. My Problem is When I Type Anything the first character goes all the way to the end of the text, for an example, if I type 152 it Shows 521 and When I cleared the TextBox using keyboard(Back Space key), and Type again it works Perfactly.


Solution

  • Instead of going for all this troubles I suggest you to simply add a label to the right of the textbox and put a % as the label's text.

    However, if you really want to go for the TextChanged path then you need to test if your input ends with the % char and add it only if not. Also you need to set the position where the next char should be typed.

    if (skipTextChange)
        skipTextChange = false;
    else
    {
        skipTextChange = true;
        if (PercentageText.Text == "")
        {
            PercentageText.Text = " ";
        }
        if (!PercentageText.Text.EndsWith("%"))
        {
            PercentageText.Text = "" + PercentageText.Text.Trim() + "%";
            PercentageText.SelectionStart = PercentageText.TextLength - 1;
        }
    }
    

    Consider to test extensively with this approach. Copy/Paste, Delete and BackSpace behavior should be verified and insertion of multiple spaces or with the case of a % char typed directly by the user. Of course, if this textbox is supposed to contain only numbers a more complex verification code is required. If this is the context then I suggest to use NUmericUpDown control and the label trick to its right.