Restricting users to input only numbers in C# windows application

后端 未结 6 664
小鲜肉
小鲜肉 2020-12-30 11:19

I have tried this code to restrict only numbers.It type only numbers and don\'t make entry when we try to enter characters or any other controls, even it doesnt enter backsp

6条回答
  •  攒了一身酷
    2020-12-30 12:17

    You do not need to use a RegEx in order to test for digits:

    private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
         if (!Char.IsDigit(e.KeyChar))
              e.Handled = true;
    }
    

    To allow for backspace:

    private void TxtBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
         if (!(Char.IsDigit(e.KeyChar) || (e.KeyChar == (char)Keys.Back)))
              e.Handled = true;
    }
    

    If you want to add other allowable keys, look at the Keys enumeration and use the approach above.

提交回复
热议问题