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

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

提交回复
热议问题