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();
                }
            }
        }
相关推荐
lalala_Zou3 分钟前
某大厂后端一面
java·开发语言
W23035765733 分钟前
Linux C++ 基于 timerfd + epoll 实现高性能定时器队列(完整源码 + 超详细解析)
linux·开发语言·c++·线程池
WL_Aurora13 分钟前
Java技术体系:JDK、JRE、JVM的关系与演进(2026最新版)
java·开发语言·jvm
吃好睡好便好18 分钟前
在Matlab中绘制二维等高线图
开发语言·人工智能·学习·算法·matlab
wkj00119 分钟前
JavaScript模块化技术进程详解
开发语言·javascript·ecmascript
2zcode20 分钟前
基于Matlab元胞自动机模拟(CA)动态再结晶过程
开发语言·matlab·动态再结晶
Gerardisite20 分钟前
企业微信怎么玩?用 API 打造智能私域助手
开发语言·python·机器人·企业微信
buhuizhiyuci23 分钟前
【QT-百日筑基篇】打完完怪,开始学炼丹, 前往藏书阁寻找对应材料的信息,并前往去寻找对应材料-QT信号和槽
开发语言·qt
csbysj202026 分钟前
Bootstrap5 Jumbotron 深入解析
开发语言
郝学胜-神的一滴30 分钟前
CMake 010 :一步到位链接静态库
开发语言·c++·qt·程序人生·系统架构·cmake