C# NumericUpDown 控件正整数输入控制

用到了控件的 KeyPress 和 KeyUp事件。

KeyPress 中控制输入"点、空格,负号";

KeyUp 中防止删空,以及防止输入超过最大值或最小值 。

复制代码
        private void nudStart_KeyPress(object sender, KeyPressEventArgs e)
        {
            numericUpDownKeyPress(sender, e);
        }

        private void nudStart_KeyUp(object sender, KeyEventArgs e)
        {
            numericUpDownKeyUp(nudStart, sender, e);
        }

        private void numericUpDownKeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '.')
            {
                e.Handled = true;
            }
            else if (e.KeyChar == '-')
            {
                e.Handled = true;
            }
            else if (e.KeyChar == ' ')
            {
                e.Handled = true;
            }
        }

        private void numericUpDownKeyUp(NumericUpDown numericUpDown, object sender, KeyEventArgs e)
        {
            UpDownBase UpDowns = (UpDownBase)numericUpDown;
            if (UpDowns.Text == "")
            {
                numericUpDown.Text = numericUpDown.Value.ToString();
            }
            else
            {
                int value = Convert.ToInt32(UpDowns.Text);
                if (value > numericUpDown.Maximum)
                {
                    value = Convert.ToInt32(numericUpDown.Maximum);
                    numericUpDown.Value = value;
                    numericUpDown.Text = numericUpDown.Value.ToString();
                }
                else if (value < numericUpDown.Minimum)
                {
                    value = Convert.ToInt32(numericUpDown.Minimum);
                    numericUpDown.Value = value;
                    numericUpDown.Text = numericUpDown.Value.ToString();
                }
            }
        }
相关推荐
输出输入1 分钟前
前端核心技术
开发语言·前端
加油,小猿猿1 分钟前
Java开发日志-双数据库事务问题
java·开发语言·数据库
薛定谔的猫喵喵7 分钟前
天然气压力能利用系统综合性评价平台:基于Python和PyQt5的AHP与模糊综合评价集成应用
开发语言·python·qt
独好紫罗兰20 分钟前
对python的再认识-基于数据结构进行-a004-列表-实用事务
开发语言·数据结构·python
gjxDaniel21 分钟前
Objective-C编程语言入门与常见问题
开发语言·objective-c
choke23331 分钟前
[特殊字符] Python异常处理
开发语言·python
云中飞鸿32 分钟前
linux中qt安装
开发语言·qt
少控科技1 小时前
QT第6个程序 - 网页内容摘取
开发语言·qt
darkb1rd1 小时前
八、PHP SAPI与运行环境差异
开发语言·网络安全·php·webshell
历程里程碑1 小时前
Linux20 : IO
linux·c语言·开发语言·数据结构·c++·算法