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();
                }
            }
        }
相关推荐
mudtools3 小时前
.NET驾驭Word之力:理解Word对象模型核心 (Application, Document, Range)
c#·.net
侃侃_天下8 小时前
最终的信号类
开发语言·c++·算法
echoarts9 小时前
Rayon Rust中的数据并行库入门教程
开发语言·其他·算法·rust
Aomnitrix9 小时前
知识管理新范式——cpolar+Wiki.js打造企业级分布式知识库
开发语言·javascript·分布式
大飞pkz9 小时前
【设计模式】C#反射实现抽象工厂模式
设计模式·c#·抽象工厂模式·c#反射·c#反射实现抽象工厂模式
每天回答3个问题10 小时前
UE5C++编译遇到MSB3073
开发语言·c++·ue5
伍哥的传说10 小时前
Vite Plugin PWA – 零配置构建现代渐进式Web应用
开发语言·前端·javascript·web app·pwa·service worker·workbox
小莞尔10 小时前
【51单片机】【protues仿真】 基于51单片机八路抢答器系统
c语言·开发语言·单片机·嵌入式硬件·51单片机
我是菜鸟0713号11 小时前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_11 小时前
QT(4)
开发语言·汇编·c++·qt·算法