Hooking Up to Events

In the Code Editor, IntelliSense can help you hook up methods (event handlers) to event fields. See the Events Tutorial for more conceptual information.

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

If you press TAB, then IntelliSense automatically completes 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.

Note   If your new delegate (created by IntelliSense) references an existing event handler, then IntelliSense conveys this information in the ToolTip. You can then modify this reference, as the text is already selected in the Code Editor. Otherwise, automatic event hook up is complete at this point.

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

Note   Use the Navigate Back command (CTRL+-) to go back to the event hookup statement.

Example

This example shows how IntelliSense automatically hooks up an event handler named button1_Click to an event field named button1.Click.

To hook up to an event

  1. Create a C# Windows application.

  2. Drag a Button control from the Windows Forms tab in the Toolbox onto your 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 places 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

Visual C# IntelliSense