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();
                }
            }
        }
相关推荐
QX_hao21 分钟前
【Go】--map和struct数据类型
开发语言·后端·golang
你好,我叫C小白25 分钟前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
Evand J2 小时前
【MATLAB例程】基于USBL和DVL的线性回归误差补偿,对USBL和DVL导航数据进行相互补偿,提高定位精度,附代码下载链接
开发语言·matlab·线性回归·水下定位·usbl·dvl
爱喝白开水a3 小时前
LangChain 基础系列之 Prompt 工程详解:从设计原理到实战模板_langchain prompt
开发语言·数据库·人工智能·python·langchain·prompt·知识图谱
Neverfadeaway3 小时前
【C语言】深入理解函数指针数组应用(4)
c语言·开发语言·算法·回调函数·转移表·c语言实现计算器
武子康3 小时前
Java-152 深入浅出 MongoDB 索引详解 从 MongoDB B-树 到 MySQL B+树 索引机制、数据结构与应用场景的全面对比分析
java·开发语言·数据库·sql·mongodb·性能优化·nosql
杰克尼3 小时前
JavaWeb_p165部门管理
java·开发语言·前端
一成码农4 小时前
JavaSE面向对象(下)
java·开发语言
偶尔的鼠标人4 小时前
Avalonia DataGrid 控件的LostFocus事件会多次触发
开发语言·c#
晚风残4 小时前
【C++ Primer】第十二章:动态内存管理
开发语言·c++·c++ primer