如何在NumericUpDown中保留有效值,而不是分配最大值? [英] How to keep valid value in NumericUpDown instead assigning Maximum value?

查看:166
本文介绍了如何在NumericUpDown中保留有效值,而不是分配最大值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有带有Maximum = 99Minimum = -99且初始值= 23的NumericUpDown.如果用户将焦点设置到此控制并输入1(现在为123),它将其值更改为99. 如何保持23而不是将值更改为允许的最大值?

Say I have NumericUpDown with Maximum = 99 and Minimum = -99 and initial value = 23. If user sets focus to this contol and inputs 1 (that would be 123 now) it changes it's value to 99. How do I keep 23 instead changing value to maximum allowed?

我尝试捕获KeyDown和KeyPress,但在此事件期间未更改值.我也尝试实施

I tried to catch KeyDown and KeyPress, but value wasn't changed during this events. Also I tried to implement a workaround explained in this question, but not succeeded. Validating event occurs only on leaving control. I need to simply ignore user input if it's greater than Maximum or lesser than Minimum.

UPD.我正在使用 WinForms .

UPD. I'm using WinForms.

推荐答案

好,我找到了

Ok, I found solution with this question help. I tried many combinations and found one that wasn't too complicated. I save old value on KeyDown event and check it on textBox.TextChanged event. At that time value haven't changed yet. Now numericUpDown visually discards input that will be not in Minimum...Maximum range. Not user-friendly I think, there is some work to do.

public partial class Form1
{
   private decimal _oldValue;
   private TextBox textBox;

   public Form1()
   {
      InitializeComponent();

      textBox = (TextBox)numericUpDown.Controls[1];
      textBox.TextChanged += TextBoxOnTextChanged;
   }

   private void TextBoxOnTextChanged(object sender, EventArgs eventArgs)
    {
        decimal newValue = Convert.ToDecimal(((TextBox) sender).Text);
        if (newValue > numericUpDown.Maximum || newValue < numericUpDown.Minimum)
            ((TextBox) sender).Text = _oldValue.ToString();
    }

   private void numericUpDown_KeyDown(object sender, KeyEventArgs e)
   {
      _oldValue = ((NumericUpDownCustom) sender).Value;
   }
}

这篇关于如何在NumericUpDown中保留有效值,而不是分配最大值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆