Skip Navigation Links.
Declaring Events with C#
Language(s):C#
Category(s):Events
One of the first hurdles for VB.Net Developers when learning C# is the difference in using and declaring events. This article will show how to declare events for Controls as well as using events in a class.

First of all, let's look at declaring events in a Form or Control. VB.Net and VB 6.0 programmers are used to bringing up the Code Editor, choosing an object in the Class Dropdown and then selecting the appropriate event name from the Methods Dropdown. It would make sense to do it the same way in C# and when the world makes sense it will be this way - but today is not that day. However, the good news is that it is just as easy - just done a different way.

Let's say we want to declare some code to trap the Form_Closing event. In C# you do this from Property Page Windows of the Design View. Or - in English - bring up the Form in the Designer, press F4 and then click the button with the little lightning bolt. Click on the appropriate event and double-click. See the illustration below:


You can also do the same with code. This time, let's add a TextBox to the form and declare an event handler for the KeyPress event using code. The first thing to do is to write the function that will accept the event. This function must be declared correctly - that is as a standard event with object and EventArgs arguments. Suppose we want to call our routine textBox1_KeyPress. We would declare the routine as follows:

    protected void textBox1_KeyPress(object sender, EventArgs e)

    {

        //Todo - process the event here

    }

 

 

 

 

 

So far so good - but we still need to connect the function with the event itself. We do this by using the += operator as follows:

    private void frmMain_Load(object sender, EventArgs e)

    {

        textBox1.KeyPress += textBox1_KeyPress;

    }

The syntax does seem a bit weird if you ask me but if it works it works.

Next: Declaring Events from a Class

This article has been viewed 10120 times.
The examples on this page are presented "as is". They may be used in code as long as credit is given to the original author. Contents of this page may not be reproduced or published in any other manner what so ever without written permission from Idioma Software Inc.