简体   繁体   中英

.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.

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".

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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