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();
                }
            }
        }

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-02 03:24:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-02 03:24:01       100 阅读
  3. 在Django里面运行非项目文件

    2024-04-02 03:24:01       82 阅读
  4. Python语言-面向对象

    2024-04-02 03:24:01       91 阅读

热门阅读

  1. 阿里巴巴实习面经

    2024-04-02 03:24:01       41 阅读
  2. 竞赛常考的知识点大总结(二)基础算法

    2024-04-02 03:24:01       34 阅读
  3. vue3中computed详解

    2024-04-02 03:24:01       42 阅读
  4. vue——computed和methods的区别

    2024-04-02 03:24:01       30 阅读
  5. Vue 使用 array.flatMap()例子

    2024-04-02 03:24:01       33 阅读
  6. 远程过程调用-buttonrpc源码解析6-函数调用

    2024-04-02 03:24:01       37 阅读
  7. vue Props

    2024-04-02 03:24:01       32 阅读
  8. 【题解 | 01背包】分割等和子集

    2024-04-02 03:24:01       38 阅读
  9. nginx怎么配置https访问

    2024-04-02 03:24:01       31 阅读
  10. [lesson01]学习C++的意义

    2024-04-02 03:24:01       35 阅读
  11. Pytorch实用教程: torch.tensor()的用法

    2024-04-02 03:24:01       35 阅读
  12. js的date对象有什么用

    2024-04-02 03:24:01       35 阅读
  13. 【开发总结】electron浏览器打开踩坑

    2024-04-02 03:24:01       33 阅读