首页 > 解决方案 > .Focus() 在 TextChangedEvent 中不起作用

问题描述

我已经在我的 Windows 窗体 C# 程序中实现了一些代码,问题是我想使用以下代码TextChangeEvent而不是Validating事件,但是.Focus()and.Select()方法不起作用。

解决方案是什么?

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

标签: c#winformsfocustextchanged

解决方案


如果您试图强制用户只能在文本框中键入单词“John”,并且您想在每次按键时验证这一点,那么您可以执行以下代码,它检查当前文本,一个一个字符,并将每个字符与单词“John”中的对应字符进行比较。

如果一个字符不匹配,那么我们将文本设置为仅匹配字符的子字符串,这样他们就可以继续输入:

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;
}

推荐阅读