簡體   English   中英

每次按下Winforms TextBox時如何獲取當前文本?

[英]How to get the current text after each key press in a Winforms TextBox?

我試圖在用戶輸入到TextBox時過濾ListView中的項目列表,並使用KeyDownKeyPress事件,但是當我讀取textbox.Text ,它總是返回上次按鍵之前的文本。 有沒有一種方法可以始終獲取TextBox顯示的內容而無需按Enter鍵?

使用TextBox.TextChanged事件(從Control繼承)。

當Text屬性值更改時發生。

我的建議是盡量不要通過按鍵事件(下/下/上)來破解它-還有其他更改文本框文本的方法,例如通過右鍵單擊上下文菜單粘貼文本。 這不涉及按任何鍵。

您可以使用有問題的TextBox的TextChanged事件。 我認為KeyUp事件也可能會起作用。

對於實際的原始問題,以前的答案是不完整的:當用戶剛剛按下一個鍵(包括該鍵)時,如何檢索Text屬性的內容?

在實際更改Text屬性的內容之后 ,會觸發KeyUp事件,因此使用此特定事件順序,您可以僅使用KeyUp事件處理程序來檢索文本內容的最新值。

KeyPress事件不起作用,因為在Text屬性更改之前會觸發該事件。

 public static string NextControlValue(string originalValue, int selectStart, int selectLength, string keyChar)
    {
        if (originalValue.Length > selectStart)
        {
            if (selectLength > 0)
            {
                originalValue = originalValue.Remove(selectStart, selectLength);
                return NextControlValue(originalValue, selectStart, 0, keyChar);
            }
            else
            {
                return originalValue.Insert(selectStart, keyChar);
            }
        }
        else
        {
            return originalValue + keyChar;
        }

    }

var previewValue = NextControlValue(textbox.Text, textbox.SelectionStart, textbox.SelectionLength, e.KeyChar + "");

您可以嘗試使用KeyPress事件:

int position = textBox1.SelectionStart;
string changedText = textBox1.Text.Insert(position, e.KeyChar.ToString());

暫無
暫無

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

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