简体   繁体   English

.Focus()在TextChangedEvent中不起作用

[英].Focus() doesn't work in TextChangedEvent

I have implemented some code in my Windows Form C# program, and the problem is that I want to have the following code in TextChangeEvent instead of the Validating event, but the .Focus() and .Select() methods don't work. 我在我的Windows Form C#程序中实现了一些代码,问题是我想在TextChangeEvent而不是Validating事件中使用以下代码,但.Focus().Select()方法不起作用。

What is the solution for this? 这是什么解决方案?

private void jTextBox5_TextChangeEvent(object sender, EventArgs e)
{
    if (jTextBox5.TextValue != "John")
    {
        jTextBox5.Focus();
    }
}

You could try: 你可以尝试:

private void jTextBox5_TextChangeEvent(object sender, EventArgs e)
{
    if (jTextBox5.Text.ToUpper().Trim() != "JOHN")
    {
        ((Textbox)sender).Focus();
}

If you're trying to enforce that the user can only type the word "John" into the textbox, and you want to validate this on each key press, then you can do something like the following code, which examines the current text, one character at a time, and compares each character to it's counterpart in the word "John". 如果您试图强制用户只能在文本框中键入单词“John”,并且您希望在每次按键时验证这一点,那么您可以执行类似以下代码的操作,该代码检查当前文本,一次一个字符,并将每个字符与单词“John”中的对应字符进行比较。

If a character doesn't match, then we set the text to only the substring of characters that do match, so they can continue typing: 如果输入的字符不匹配,那么我们将文本设置为只有那些匹配的字符的字符串,这样他们就可以继续输入:

private void jTextBox5_TextChanged(object sender, EventArgs e)
{
    var requiredText = "John";

    // Don't allow user to type (or paste) extra characters after correct word
    if (jTextBox5.Text.StartsWith(requiredText))
    {
        jTextBox5.Text = requiredText;
    }
    else
    {
        // Compare each character to our text, and trim the text to only the correct entries
        for (var i = 0; i < jTextBox5.TextLength; i++)
        {
            if (jTextBox5.Text[i] != requiredText[i])
            {
                jTextBox5.Text = jTextBox5.Text.Substring(0, i);
                break;
            }
        }
    }

    // Set the selection to the end of the text so they can keep typing
    jTextBox5.SelectionStart = jTextBox5.TextLength;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM