Search code examples
c#textboxautoformatting

C# Removing last two characters from textbox


I have a textbox which I'm trying to implement automatic formatting on for a phone number.

I would like to remove the last two characters of the textbox if the user presses the delete key and the last character of the string in the textbox is '-'.

I am attempting to do this through substring removal, but with no luck. Thanks

private void phoneNumberTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Back)
            {
                if (phoneNumberTextBox.Text.Length != 0)
                {
                    if (Convert.ToChar(phoneNumberTextBox.Text.Substring(phoneNumberTextBox.Text.Length - 1)) == '-')
                    {
                        phoneNumberTextBox.Text.Substring(0, phoneNumberTextBox.Text.Length - 2);
                    }
                }
            }     

Solution

  • Substring() returns a new string instance and leaves the current instance unchanged. Because of this, your call just creates a new temporary string but because you don't do anything with it, it gets thrown away immediately.

    To make the change stick, you need to assign the result of Substring() back to the textbox, like so:

    phoneNumberTextBox.Text = phoneNumberTextBox.Text.Substring(0,
        phoneNumberTextBox.Text.Length - 2);
    

    Make sure you check the length of the string first to avoid problems with handling short string (less than 2 characters).

    Also, if you want to limit the number of characters in the textbox, just use the MaxLength property instead. You don't have to deal with handling length and typing that way.