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();
                }
            }
        }
相关推荐
她说..20 分钟前
Java 对象相关高频面试题
java·开发语言·spring·java-ee
watson_pillow1 小时前
c++ 协程的初步理解
开发语言·c++
庞轩px1 小时前
深入理解 sleep() 与 wait():从基础到监视器队列
java·开发语言·线程··wait·sleep·监视器
故事和你911 小时前
洛谷-算法1-2-排序2
开发语言·数据结构·c++·算法·动态规划·图论
白毛大侠2 小时前
理解 Go 接口:eface 与 iface 的区别及动态性解析
开发语言·网络·golang
李昊哲小课3 小时前
Python办公自动化教程 - 第7章 综合实战案例 - 企业销售管理系统
开发语言·python·数据分析·excel·数据可视化·openpyxl
Hou'3 小时前
从0到1的C语言传奇之路
c语言·开发语言
不知名的老吴3 小时前
返回None还是空集合?防御式编程的关键细节
开发语言·python
迈巴赫车主3 小时前
蓝桥杯3500阶乘求和java
java·开发语言·数据结构·职场和发展·蓝桥杯
小菜鸡桃蛋狗3 小时前
C++——string(上)
开发语言·c++