如何将重点放在显示为对话框的表单中的文本框上? [英] How to focus on a textbox from a Form shown as a dialog?

查看:120
本文介绍了如何将重点放在显示为对话框的表单中的文本框上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框,当用户输入无效数据并离开文本框时,ShowDialog方法将显示一个表单,通知该数据无效并询问用户是否要重新输入.如果他/她想要,则应在文本框中设置FOCUS.但这并不简单.这是我的代码:

I have a textbox, when a user input invalid data and leave the textbox, a form will be displayed by the ShowDialog method to inform that the data is invalid and ask if the user wants to re-enter. If he/she wants that, it should set FOCUS on the textbox. But it is not simple. Here is my code:

private void OnLostFocus(object sender, EventArgs e)
{
   if(ReEnter) 
   {
     ReEnter = false;
     return;
   }
   if(!IsValidData()) 
   {
    MsgBox M = new MsgBox();
    M.ShowDialog();
    if(M.DialogResult = DialogResult.OK)
      {
        ReEnter = true;
        textBox1.Focus();
      }
   }
}


IsValidData()是我检查数据是否有效的方法,我的ReEnter用来标记用户要重新输入.
我认为它应该起作用,但是它以一种非常奇怪的方式起作用,即使ReEnter永远都不会实现(当确定接受重新输入时),这将导致隐藏和显示对话框的循环.我无法使其按需运行.您能否请查看并检查和测试您自己的代码以帮助我解决此问题.我希望每当用户离开文本框时都会执行数据有效性检查!
非常感谢!


IsValidData() is my method to check if the data is valid, my ReEnter is to mark that the user wants to re-enter.
I think it should work, but it works a very strange way, even the ReEnter never comes true (when OK accepted to re-enter), that makes a loop of hiding and showing the dialog. I can''t make it work as I want. Could you please see and check and test your own code to help me out of this problem. I want the data validity check will be fulfiled whenever the user leaves the textbox!
Thank you so much!

推荐答案

如果数据无效,请使用IsValidData()方法调用textBox1.Focus()方法,而不要使用ReEnter变量和事件. .
Call the textBox1.Focus() method on the IsValidData() method if the data is not valid instead of using the ReEnter variable and events.


Hi应该是if(M.DialogResult == DialogResult.OK). Single =是赋值运算符,不是比较运算符.如果它是一个简单的消息框,则可以使用内置的System.Windows.Forms.MessageBox.不需要单独的表格.

祝你好运
Hi should be if(M.DialogResult == DialogResult.OK). Single = is an assignment operator, not compare operator. If it is a simple message box you can use inbuilt System.Windows.Forms.MessageBox. No need a separate form.

Good luck


这篇关于如何将重点放在显示为对话框的表单中的文本框上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆