C#限制控件内容只允许输入数字

找到该控件的KeyPress事件,在该事件内写入代码即可完成

        if (e.KeyChar == 0x20) e.KeyChar = (char)0;  //禁止空格键
            if (e.KeyChar == (char)46) e.KeyChar = (char)0;
            if (e.KeyChar == (char)44)
                e.KeyChar = (char)0;
            if (e.KeyChar == (char)45)
                e.KeyChar = (char)0;
            if ((e.KeyChar == 0x2D) && (((TextBox)sender).Text.Length == 0)) return;   //处理负数
            if (e.KeyChar > 0x20)
            {
                try
                {
                    double.Parse(((TextBox)sender).Text + e.KeyChar.ToString());
                }
                catch
                {
                    e.KeyChar = (char)0;
                }
            }

 

你可能感兴趣的:(C#)