简体   繁体   中英

C# inputs an ASCII character to the TextBox when I press Backspace

I have used e.Handled bool of KeyPress event and let e.KeyChar only be D0-D9, ',' and Back. But then my program started inputting an ASCII character into the TextBox instead of erasing the most recent char when I pressed Backspace. Then I assigned;

if(e.KeyChar == (char)Keys.Back) {textBox1.Text = textBox1.Text + "\\b"}

to erase the most recent char that was inputted. It still decided to input a weird ASCII character instead of erasing anything.

If you want to allow characters in '0'..'9' range only, while keeping all the other logic intact (for instance, if you select several characters and then press "BackSpace" only selection will be removed, not the last character) you can handle unwanted characters only:

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) {
  e.Handled = e.KeyChar >= ' ' && (e.KeyChar < '0' || e.KeyChar > '9');
}

Note, that e.KeyChar >= ' ' allowes all command characters (BS included)

this worked:

if (e.KeyChar == (char)Keys.Back)
        {
            textBox1.Text = textBox1.Text.Substring(0, (textBox1.Text.Length - 1));
        }

Please try with the following code.

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar != (char)Keys.Back &&
            (e.KeyChar < (char)Keys.D0 || e.KeyChar > (char)Keys.D9))
        {
            e.Handled = true;
        }
    }

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