【问题标题】:How do I access the text of a NumericUpDown control before it's validated?如何在验证之前访问 NumericUpDown 控件的文本?
【发布时间】:2011-12-16 22:19:44
【问题描述】:

我有一个带有 System.Windows.Forms.NumericUpDown 控件的表单。

假设范围是从 0 到 100,当前值(通过微调器到达)是 100。我可以输入一个超出允许范围的数字(比如 567),但是当我单击“确定”时表单重置值,它只是默默地将超出范围的值设置为 100 并关闭表单。

客户想要一个明确的消息,说明号码超出范围。因此,我查看了关闭表单上的 NumericUpDown.Text 属性,但该属性返回的是“100”而不是“567”。

我可以在哪里(或如何)“捕捉”控件中出现的文本是“567”这一事实?

【问题讨论】:

    标签: .net winforms validation .net-2.0 numericupdown


    【解决方案1】:

    您可以使用来自this question 的答案通过在NumericUpDown 中获取对TextBox 的引用并处理其Validating 事件来捕获无效值。在您的处理程序中,TextBox.Text 属性将具有要测试的无效值。在 .NET 2.0 Winforms 中为我工作。

    【讨论】:

    • 这是我想要的漂亮。谢谢!
    【解决方案2】:

    您可以试试这个,唯一的问题是该值仍将重置为 100,但仍会通知用户超出范围值:

    private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            {
                int val = Convert.ToInt32(((UpDownBase)numericUpDown1).Text);
    
                if (val > 100)
                {
                    MessageBox.Show("The value " + ((UpDownBase)numericUpDown1).Text + 
                    " is out of range", "Validation Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    
                    e.Cancel = true;
                }
            }
    

    【讨论】:

    • 感谢您抽出宝贵时间回答。这会有所帮助。 ++
    猜你喜欢
    • 2022-12-07
    • 1970-01-01
    • 2013-01-02
    • 2022-01-02
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多