How to make TextBox to receive only number key values using KeyDown Event in C#?

本秂侑毒 提交于 2019-12-01 12:31:28

When you press a key, a character is already appended to your TextBox. Then you run the following code and, if the key represents a number, you append it again:

if (char.IsNumber((char)e.KeyCode)) {
    textBox1.Text += (char)e.KeyCode;
}

If you want to suppress any key that's not a number, you could use this instead:

e.SuppressKeyPress = !char.IsNumber((char)e.KeyCode);

From the syntax I assume you are using WinForms for the following answer.

The key pressed event is not suppressed, so it still works like a normal key pressed event and adds the character to the text of the box. Additionally you add the character to the text yourself once again.

Try to suppress the key pressed event in case a key is pressed, you do not want to allow.

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    if (!char.IsNumber((char)e.KeyCode))
    {
        e.SuppressKeyPress = true;
    }
}

You can try like this:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
   e.SuppressKeyPress = !(e.KeyValue >= 48 && e.KeyValue <= 57);
}

Check New keyboard APIs: KeyEventArgs.SuppressKeyPress

The problem is that "Handled" doesn't take care of pending WM_CHAR messages already built up in the message queue - so setting Handled = true does not prevent a KeyPress from occurring.

In order not to break anyone who has currently got e.Handled = true, we needed to add a new property called SuppressKeyChar. If we went the other way, if "handling" a keydown suddenly started to actually work, we might break folks who accidentally had this set to true.

Swarup

Try this code to accept numbers only

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (!char.IsDigit(e.KeyChar) && !char.IsControl(e.KeyChar))
        e.Handled = true;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!