How to: Hook Up Events By Using IntelliSense (C#)

In the Code Editor, IntelliSense can help you hook up methods (event handlers) to event fields.

When you type the += operator after an event field in a .cs file, IntelliSense prompts you with the option to press the TAB key. This inserts a new instance of a delegate that points to the method handling the event.

Button Auto Hook Up

If you press TAB, IntelliSense automatically finishes the statement for you and displays the event handler reference as selected text in the Code Editor. To complete the automatic event hookup, IntelliSense prompts you to press the TAB key again to create an empty stub for the event handler.

Generate Event Handler

Note

If a new delegate that is created by IntelliSense references an existing event handler, IntelliSense communicates this information in the tooltip. You can then modify this reference; the text is already selected in the Code Editor. Otherwise, automatic event hookup is complete at this point.

If you press TAB, IntelliSense stubs out a method with the correct signature and puts the cursor in the body of your event handler.

Note

Use the Navigate Backward command on the View menu (CTRL+-) to go back to the event hookup statement.

The following task shows how IntelliSense automatically hooks up an event handler named button1_Click to an event field named button1.Click.

To hook up to a C# event

  1. Create a C# Windows application.

  2. Drag a Button control from the Windows Forms tab in the Toolbox onto the form, and then use the View Code command to open Form1.cs in the Code Editor.

  3. In the form constructor, type the event field button1.Click, and then type the += operator. For example:

    this.button1.Click +=
    

    IntelliSense prompts you to press TAB to automatically hook up the event.

  4. Press TAB.

    IntelliSense creates a new instance of the EventHandler delegate with a reference to an event handler named button1_Click.

    this.button1.Click +=new EventHandler(button1_Click);
    

    Because button1_Click does not exist, IntelliSense prompts you to press TAB again so that it can create this method.

  5. Press TAB.

    IntelliSense creates the method button1_Click() and then puts the cursor in the body so that you can immediately continue adding code to this event handler.

    private void button1_Click(object sender, EventArgs e)
    {
    
    }
    

See Also

Other Resources

Visual C# IntelliSense

Automatic Code Generation