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();
                }
            }
        }
相关推荐
Boop_wu34 分钟前
[Java EE] 多线程 -- 初阶(5) [线程池和定时器]
java·开发语言
小小编程能手38 分钟前
大小端字节序
c#
S***H2831 小时前
JavaScript原型链继承
开发语言·javascript·原型模式
kk”1 小时前
C++ map
开发语言·c++
车端域控测试工程师1 小时前
Autosar网络管理测试用例 - TC003
c语言·开发语言·学习·汽车·测试用例·capl·canoe
共享家95271 小时前
特殊类的设计
开发语言·c++
嘟嘟w2 小时前
JVM(Java 虚拟机):核心原理、内存模型与调优实践
java·开发语言·jvm
信奥卷王2 小时前
2025年9月GESPC++三级真题解析(含视频)
开发语言·c++·算法
喵了几个咪2 小时前
Golang微服务框架kratos实现Socket.IO服务
开发语言·微服务·golang
q***42052 小时前
PHP使用Redis实战实录2:Redis扩展方法和PHP连接Redis的多种方案
开发语言·redis·php