Hooking Events in C#


Where’s C# Control Events? It’s gone!

Wait a sec, there’s something wrong with my Visual Studio. I can’t see the events that are available to my control just like Visual Basic.

Are you one of those who keep asking this question? Perhaps some of you wonder how to add Events in your application in C#.NET then this topic is for you.

Maybe this topic is just a waste of time but I hope this will stop scratching your head where to find the events in Visual Studio 2005 or the Express Editions and C#.NET.

(I would like to relate this post to the person named NWeb from asp.net forum. He wasted a day till he finds out how to pass parameters in MySQL. Lol)

There are few ways on how to create your events in C# with your Visual Studio 2005 or Express Editions. We can hook up events using Intellisense

 


type or initialize it yourself, or just enjoy the beauty of Visual Studio with a few mouse clicks.

In your Property windows, you can see an extra lightning icon in the right-side with a little “cute” tip labeled “Events”. See image below.


After clicking that icon, it will list available events. The good part is that you can name it yourself. Like if you want controlname_GotFocus to be controlname_WhenFocused you can easily type it in the field.

The other way of doing it is to initialize the event yourself. Before Visual Studio 2005 I used Visual Studio 2003. The InitializeComponent() method in VS 2003 can be shown in the Code view but right after VS 2005 it can only be seen when selecting it in the events selections.

 


(Initializing your events can be useful when starting to create your own system events).

So anyway, in our InitializeComponent method will create a delegate to represent our control event. Let’s say for example we want to handle the event for a Textbox GotFocus event then it should look like


textBox1.GotFocus += new System.EventHandler(textBox1_GotFocus);


and in our handler could look like


void textBox1_GotFocus(object sender, System.EventArgs e)
{
    // statements here…
}


So that’s it. No big deal.

Good luck!

 

Leave a Reply