Problem solve Get help with specific problems with your technologies, process and projects.

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

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));

Dig Deeper on C# programming language

Have a question for an expert?

Please add a title for your question

Get answers from a TechTarget expert on whatever's puzzling you.

You will be able to add details on the next page.

Start the conversation

Send me notifications when other members comment.

Please create a username to comment.