如何在失去焦点后保持NumericUpDown的无效值?

在我的项目中有一个UserControl,它包含一个NumericUpDown ctrl,其有效值范围是10到100

所以如果用户在NumericUpDown ctrl中输入200,那么在焦点改变为其他ctrl后它的值会自动变为100,对于客户来说它看起来有点好奇,因为他们可能会在NumericUpDown ctrl中输入200之后点击OK按钮,需要一个消息框,告诉他们输入的值不在范围内。

但问题是,如果值输入超出其范围,NumericUpDown的值将在焦点更改后自动更改。

那么如何实现呢?

Sameh Serag,这是我测试过的代码。 我在表单上添加了一个按钮,但什么也没做。 我的结果是在输入200并单击按钮后,只显示值为100的消息框。 输入200并按Tab键后,它只会显示一个值为200的消息框,并且NumericUpDown中的文本值更改为100.好奇:-)无论如何,非常感谢你的帮助! 顺便说一句,.Net框架版本是2.0,sp2对我来说。

public partial class Form1 : Form { private TextBox txt; public Form1() { InitializeComponent(); txt = (TextBox)numericUpDown1.Controls[1]; txt.Validating += new CancelEventHandler(txt_Validating); } void txt_Validating(object sender, CancelEventArgs e) { MessageBox.Show(txt.Text); } } 

诀窍是将文本框嵌入到数字更新控件中,并处理其Validating事件。

以下是如何完成它:

创建一个虚拟表单并添加一个数字更新控件和一些其他控件,当数字下拉控件失去焦点时,表单的文本将设置为用户输入的值。

这是我所做的代码:

 public partial class Form1 : Form { TextBox txt; public Form1() { InitializeComponent(); txt = (TextBox)numericUpDown1.Controls[1];//notice the textbox is the 2nd control in the numericupdown control txt.Validating += new CancelEventHandler(txt_Validating); } void txt_Validating(object sender, CancelEventArgs e) { this.Text = txt.Text; } } 

编辑:

@Carlos_Liu:好的,我现在可以看到问题了,你可以用TextChanged事件来实现这个,只需将值保存在虚拟变量中并在txt_Validating中重用它,但要小心, 不要更新这个变量,除非文本框是专注的

这是新的示例代码:

 public partial class Form1 : Form { TextBox txt; string val; public Form1() { InitializeComponent(); txt = (TextBox)numericUpDown1.Controls[1];//notice the textbox is the 2nd control in the numericupdown control txt.TextChanged += new EventHandler(txt_TextChanged); txt.Validating += new CancelEventHandler(txt_Validating); } void txt_TextChanged(object sender, EventArgs e) { if (txt.Focused) //don't save the value unless the textbox is focused, this is the new trick val = txt.Text; } void txt_Validating(object sender, CancelEventArgs e) { MessageBox.Show("Val: " + val); } } 

编辑#2

@Carlos_Liu:如果你需要保留输入的值,仍然有一个技巧:@文本框的validation事件,检查值,如果它不在范围内,取消失去焦点!

这是代码的新版本:

 public partial class Form1 : Form { TextBox txt; string val; public Form1() { InitializeComponent(); txt = (TextBox)numericUpDown1.Controls[1]; txt.TextChanged += new EventHandler(txt_TextChanged); txt.Validating += new CancelEventHandler(txt_Validating); } void txt_TextChanged(object sender, EventArgs e) { if (txt.Focused) val = txt.Text; } void txt_Validating(object sender, CancelEventArgs e) { int enteredVal = 0; int.TryParse(val, out enteredVal); if (enteredVal > numericUpDown1.Maximum || enteredVal < numericUpDown1.Minimum) { txt.Text = val; e.Cancel = true; } } }