Search code examples
c#winformstextboxkeypress

Delete the last character when a key is pressed on a textbox C#


I'm trying to block the user press the same key (by example if the user have "asd" in a TextBox and the user press "x" the text box still contains "asd" but don't insert "x"), I have tried using KeyDown and KeyUp but it delete the last character but insterts the pressed ("asx" it deletes "d"). Sorry for my bad english.

private void txtInsert_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == 104) //I'm trying to delete "h"
        {
            string cadena = txtInsert.Text;
            cadena = cadena.Substring(0, cadena.Length - 1);
            txtInsert.Text = cadena;
            string cadena = "";
            for (int i = 0; i < txtInsert.TextLength-1; i++)
            {
                cadena += txtInsert.Text[i];
            }
            txtInsert.Text = "";
            txtInsert.Text = cadena;
        }
    }

Solution

  • Try KeyPress event (so we have char to operate with, not key which can be, say, left shift) and Handled in order to prevent user input (WinForms example):

    private void myTextBox_KeyPress(object sender, KeyPressEventArgs e) {
      TextBox box = sender as TextBox;
    
      // Do nothing if 
      e.Handled = 
        e.KeyChar >= ' ' &&    // key is not control one (e.g. not backspace)
        box.Text.Length >= 3;  // Text Box Text has Length >= 3
    }
    

    If you want to prevent adding 'h'

      // Do nothing on 'h' character
      e.Handled = e.KeyChar == 'h';