How to get the current text after each key press i

2019-08-09 11:32发布

问题:

I am trying to filter a list of items in a ListView as the user types into a TextBox and I use KeyDown, and KeyPress events but when I read the textbox.Text, it always returns the text before the last key press. Is there a way to always get whatever is shown in the TextBox without pressing enter?

回答1:

Use the TextBox.TextChanged event (inherited from Control).

Occurs when the Text property value changes.

My advice is to try not to hack this with the key events (down / press / up) - there are other ways to change a text-box's text, such as by pasting text from the right-click context menu. This doesn't involve pressing a key.



回答2:

You could use the TextChanged event of the TextBox in question. I think the KeyUp event might work as well.



回答3:

Use the KeyPressEventArgs.KeyChar Property.



回答4:

The previous answers are incomplete with regards to the actual original question: how to retrieve the contents of the Text property when the user has just pressed a key (and including that keypress)?

The KeyUp event happens to be fired AFTER the contents of the Text property actually change, so using this particular order of events, you can retrieve the latest value of the text contents just using a KeyUp event handler.

The KeyPress event doesn't work because that gets fired BEFORE the change of the Text property.



回答5:

 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 + "");


回答6:

You can try with KeyPress event:

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