Adding Events To WinForms?

20,791

Solution 1

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
}

Solution 2

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
}

Solution 3

Doubleclick the textfield next to it.

Solution 4

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.

Share:
20,791
sooprise
Author by

sooprise

I like to program, but am a noob, which is why I'm here. <-My sexy fatbooth picture

Updated on July 24, 2020

Comments

  • sooprise
    sooprise almost 4 years

    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.