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

前端 未结 4 1561
攒了一身酷
攒了一身酷 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: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);
    

提交回复
热议问题