Pure.Krome Pure.Krome - 3 years ago 149
C# Question

TextBox.KeyPress event is missing the most recent key pressed? Huh?

I've got a

WinForm
which has a
TextBox
. I've wired up the
KeyPress
event so I can do stuff with the text in that textbox instance.

In the method that handles that event, the value of the
TextBox.Text
is the current text box content MINUS the key just pressed. I need it to be the exact text INCLUDING what key i just pessed.

for example :-


  • TextBox.Text == hello

  • I then click the
    backspace
    key.

  • The
    KeyPress
    event is fired .. the value of
    TextBox.Text ==
    "hello"
    :( I want it to equal
    "hell"
    .



And please don't say just add the
e.KeyChar
value .. because that now is
hello\b
.

Is there an event i can use that can get fired AFTER the key is pressed -and- the value of the textbox is the correct/current value?

Answer Source

You need the KeyUp event.

Key events occur in the following order:
1. KeyDown
2. KeyPress
3. KeyUp

Source: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.keyup.aspx

Also consider TextChanged if you're only working with the text and not the keys in particular.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download