Naveen Kumar V
Naveen Kumar V

Reputation: 2819

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

This code in my form updates the textBox1.Text twice whenever number keys are pressed.

private void textBox1_KeyDown( object sender, KeyEventArgs e ) {
     //MessageBox.Show();
     if( char.IsNumber((char)e.KeyCode) ) {
           textBox1.Text += (char)e.KeyCode;
     }
}

Explain why if you can? Modify the code or provide me a better solution for this.

Input ( in textbox1 ):

54321

Output:

1234554321

Upvotes: 1

Views: 2748

Answers (4)

Swarup
Swarup

Reputation: 105

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

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172588

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.

Upvotes: 1

JokoFacile
JokoFacile

Reputation: 143

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

Upvotes: 1

Grant Winney
Grant Winney

Reputation: 66489

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

Upvotes: 4

Related Questions