views:

62

answers:

5

Happy Friday! :D

I have a TextBox on a WinForm and I want to execute some code every time someone presses a key inside of that TextBox. I'm looking at the events properties menu, and see the "KeyDown" event, but don't know how to add code to it.

Happy coding

A: 

You need to add a handler to the event.

Double-click the KeyPress event in the textbox's Properties window to make Visual Studio generate an event handler in the code file.
You can then put any code you want to inside the event handler function. You can check which key was pressed by writing e.KeyCode.

SLaks
+1  A: 

Doubleclick the textfield next to it.

Femaref
+1  A: 

I assume you are in Visual Studio. One way would be to double click on the empty textbox on the right of the KeyDown event: VS will generate the code for you.

m_oLogin
+3  A: 

You need to add an event handler for that event. So in the properties menu, double-click on the field beside the KeyDown event and Visual Studio will create an event handler for you. It'll look something like this:

private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
    // enter your code here
}

You can also subscribe to events yourself without using the Properties window. For example, in the form's constructor:

textBox1.KeyDown += HandleTextBoxKeyDownEvent;

And then implement the event handler:

private void HandleTextBoxKeyDownEvent(object sender, KeyEventArgs e)
{
    // enter your code here
}
Anna Lear
I would add the fact that Visual Studio does that automatically for you in a very nice way. Start typing "textBox1.KeyDown += " and then hit the "Tab" key twice.
m_oLogin
A: 

These answers will have visual studio generate the event and bind it behind the scenes in the Designer.cs file.

If you want to know how to bind events yourself, it looks like this.

MyTextBox.KeyDown += new KeyEventHandler(MyKeyDownFunction)

private function MyKeyDownFunction(object sender, KeyEventArgs e) {
    // your code
}

If done this way, the new KeyEventHandler() part is optional. You can also use lambdas to avoid boilerplate code.

MyTextBox.KeyDown += (s, e) => {
    // s is the sender object, e is the args
}
Tesserex