只允许输入数字的TextBox控件

实现效果:

  

知识运用:

  Char结构的IsDigit方法

  TextBox控件的KeyPress事件的e(包含事件数据)的KeyChar属性和Handled属性

  1, KeyChar属性  //获取或设置按下键对应的字符

  public char KeyChar{get;set;}  //属性值: Char结构

  2, Handled属性  //指示是否处理System.Windows.Forms.Control.KeyPress事件

  public bool Handled{get;set;}

  3, IsDigit方法  //判断指定字符是否为十进制数字

  public bool IsDigit(Char c)

  补充:Char结构的IsLetter方法判断输入的字符是否为字母

实现代码:

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!char.IsDigit(e.KeyChar)) {             //判断是否为数字
                MessageBox.Show("请输入数字","提示",
                    MessageBoxButtons.OK,MessageBoxIcon.Information);
                e.Handled = true;                   //取消在控件中显示该字符
            }
        }

猜你喜欢

转载自www.cnblogs.com/feiyucha/p/10140768.html