user16413849
user16413849

Reputation:

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.

Upvotes: 0

Views: 754

Answers (3)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186823

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)

Upvotes: 1

Ming Shou
Ming Shou

Reputation: 129

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;
        }
    }

Upvotes: 0

user16413849
user16413849

Reputation:

this worked:

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

Upvotes: 0

Related Questions