簡體   English   中英

.Focus()在TextChangedEvent中不起作用

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

我在我的Windows Form C#程序中實現了一些代碼,問題是我想在TextChangeEvent而不是Validating事件中使用以下代碼,但.Focus().Select()方法不起作用。

這是什么解決方案?

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

你可以嘗試:

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

如果您試圖強制用戶只能在文本框中鍵入單詞“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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM