Joan Venge
Joan Venge

Reputation: 331590

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

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?

Upvotes: 1

Views: 10809

Answers (6)

whale70
whale70

Reputation: 375

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.

Upvotes: 2

tanyavv
tanyavv

Reputation: 1

You can try with KeyPress event:

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

Upvotes: 0

not important
not important

Reputation: 1

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

Upvotes: 0

Ani
Ani

Reputation: 113472

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.

Upvotes: 10

user325117
user325117

Reputation:

Use the KeyPressEventArgs.KeyChar Property.

Upvotes: 1

Mithrandir
Mithrandir

Reputation: 25397

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

Upvotes: 2

Related Questions