3

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

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

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

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

4

2 回答 2

7

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

于 2011-12-16T22:37:44.193 回答
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;
            }
        }
于 2011-12-16T22:44:24.780 回答