
因此,如果用户在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:如果你需要保留输入的值,仍然有一个技巧:@文本框的验证事件,检查值,如果它不在范围内,取消失去焦点!
这是代码的新版本:
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; } }} 总结 以上是内存溢出为你收集整理的c# – 如何在失去焦点后保持NumericUpDown的无效值?全部内容,希望文章能够帮你解决c# – 如何在失去焦点后保持NumericUpDown的无效值?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)