Ask the Expert

How can I attach handlers to specific events fired from the controls at runtime?

I want to develop an IDE using .NET (VB.NET or C#) for which I need to create the form and controls at runtime that can fire events. I can create the controls, but how do I create a form that responds to events at runtime? Can I do it in .NET or do I have to do it in VC++?
If you want to attach at runtime some handlers to specific events fired from the controls, you have to use reflection. First, you get a reference to the EventInfo object for the event you want to "catch":
System.Windows.Forms.ListBox myListBox = new System.Windows.Forms.ListBox();
EventInfo ei = typeof(System.Windows.Forms.ListBox).GetEvent
("SelectedIndexChanged");

Next, you can use the AddHandler to attach the method you want to it, provided the signatures match, of course:

ei.AddEventHandler(myListBox, new EventHandler(OnSelectedIndexChanged));

This was first published in June 2003

There are Comments. Add yours.

 
TIP: Want to include a code block in your comment? Use <pre> or <code> tags around the desired text. Ex: <code>insert code</code>

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy
Sort by: OldestNewest

Forgot Password?

No problem! Submit your e-mail address below. We'll send you an email containing your password.

Your password has been sent to: