numericUpDown1 值超出最大范围后返回的值(C# Windows 窗体)

问题描述 投票:0回答:1

我为“numericUpDown1”设置最小值 1 和最大值 10。 (C# Windows 窗体)

当我从键盘手动输入值 0 时,“numericUpDown1”自动增加到 1,当我从键盘手动输入大于 10 的值时,“numericUpDown1”自动减少到 10。

我可以更改这些自动退货吗?例如:如果我输入 25,它将返回 3 而不是 10。

是否有任何选项/属性可以更改此设置?

我尝试了一些选项,如“已验证”、“正在验证”、“离开”和“值更改”。但这没有用。

当<=0 or >10时,我想返回一个错误(消息框)并自动将“numericUpDown1”的值返回为1。

c# winforms validation runtime-error numericupdown
1个回答
0
投票

执行此操作的一种方法是处理

KeyDown
事件。我个人使用的方法是继承
NumericUpDown
并用我的自定义类替换 MainForm.Designer.cs 文件中的它的实例。


class NumericUpDownEx : NumericUpDown
{
    protected override void OnKeyDown(KeyEventArgs e)
    {
        base.OnKeyDown(e);
        switch (e.KeyData)
        {
            case Keys.Enter:
                e.Handled = e.SuppressKeyPress = true;
                BeginInvoke((MethodInvoker)delegate
                {
                    if (Value < 0 || Value > 10)
                    {
                        var message = $"Error: '{Value}' is not legal.";
                        Value = 1;
                        MessageBox.Show(message);
                        Focus();
                    }
                    var length = Value.ToString().Length;
                    if (length > 0)
                    {
                        Select(0, length);
                    }
                });
                break;
        }
    }
    .
    .
    .
}

当控件失去焦点时,您还需要执行相同类型的操作。

    .
    .
    .
    /// <summary>
    ///  The Validating event doesn't always fire when we 
    ///  want it to, especially if this is the onlt control.
    ///  Do this instead;
    /// </summary>
    protected override void OnLostFocus(EventArgs e) =>
        OnKeyDown(new KeyEventArgs(Keys.Enter));
© www.soinside.com 2019 - 2024. All rights reserved.