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

前端 未结 4 1559
攒了一身酷
攒了一身酷 2021-01-15 19:33

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

private void textBox1_KeyDown( object sender, KeyEventArgs e )          


        
相关标签:
4条回答
  • 2021-01-15 19:47

    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;
    }
    
    0 讨论(0)
  • 2021-01-15 19:49

    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);
    
    0 讨论(0)
  • 2021-01-15 19:52

    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;
        }
    }
    
    0 讨论(0)
  • 2021-01-15 19:56

    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.

    0 讨论(0)
提交回复
热议问题