.net(c#) winform文本框只能输入数字,不能其他非法字符

 1 private void textBox3_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)

 2 {

 3     //阻止从键盘输入键

 4     e.Handled = true;

 5     if(e.KeyChar>='0' && e.KeyChar <='9')

 6     {

 7         e.Handled = false;

 8     }

 9 

10 }

11 或者

12 private void tbID_KeyPress(object sender, KeyPressEventArgs e)

13         {

14             if (!((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == ' '))//不输入输入除了数字之外的所有非法字符的判断

15             {

16                 e.Handled = true;

17             }

18         }

19 

20 

21 多条件的:

22 

23 private void TxtUser_KeyPress(object sender, KeyPressEventArgs e)

24         {

25             //阻止从键盘输入键

26            e.Handled = true;

27 

28             if ((e.KeyChar >= '0' && e.KeyChar <= '9') || (e.KeyChar == (char)8))

29             {

30 

31                 if ((e.KeyChar == (char)8)) { e.Handled = false; return; }

32                 else

33                 {

34                     int len = TxtUser.Text.Length;

35                     if (len < 5)

36                     {

37                         if (len == 0 && e.KeyChar != '0')

38                         {

39                             e.Handled = false; return;

40                         }

41                         else if(len == 0)

42                         {

43                             MessageBox.Show("编号不能以0开头!"); return;

44                         }

45                         e.Handled = false; return;

46                     }

47                     else

48                     {

49                         MessageBox.Show("编号最多只能输入5位数字!");

50                     }

51                 }

52             }

53             else

54             {

55                 MessageBox.Show("编号只能输入数字!");

56             }

57            

58 

59         }
View Code

 

你可能感兴趣的:(WinForm)