Search code examples
c#keypressbackspace

TextBox keypress event when backspace is press in C#


It should delete the last character of string

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        do
        {

this section write character in the textbox

            if (e.KeyChar >= 48 && e.KeyChar <= 57)
            {
                textBox1.Text += e.KeyChar.ToString();
                textBox1.SelectionStart = textBox1.Text.Length;
            }

this is the backspace part that doesn't work

            if(e.KeyChar == 8)
            {
                sssnumber = textBox1.Text;
                sssnumber.Remove(sssnumber.Length - 1);
                textBox1.Text = sssnumber;
            }

        } while (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) &&
            (e.KeyChar != '.'));
        e.Handled = true;
    }

Solution

  • The issue in this code is that you are not assigning the string's value when you change it. This is because String.Remove() returns a string as opposed to changing the string directly

    sssnumber.Remove(sssnumber.Length - 1);
    

    Will remove the character from the end of the string, and then dispose of the result

    sssnumber = sssnumber.Remove(sssnumber.Length - 1);
    

    On the other hand, will do the same, but then set the value of sssnumber to the removed value.