The following snippet let you dynamically subscribe to events using C# or VB.NET.
Sample C#
//usage DynamicEventSubscription("button1", "Click", "button1_Click"); public void DynamicEventSubscription(string controlName,string eventName, string targetName, bool recursiveSearch=false) { if (controlName == String.Empty) { throw new ArgumentNullException("controlName"); } if (eventName == String.Empty) { throw new ArgumentNullException("eventName"); } if (targetName == String.Empty) { throw new ArgumentNullException("targetName"); } try { var eventMethod = GetType().GetMethod(targetName); var control = Controls.Find(controlName, false).FirstOrDefault(); if (control != null) { var eventToSubscribe = control.GetType().GetEvent(eventName); var handler = Delegate.CreateDelegate(eventToSubscribe.EventHandlerType, this, eventMethod); var button = Controls.Find(controlName, recursiveSearch).FirstOrDefault(); eventToSubscribe.AddEventHandler(button, handler); } } catch (Exception ex) { //handle the exception your way } }
Sample VB.NET
'usage DynamicEventSubscription("button1", "Click", "button1_Click") Public Sub DynamicEventSubscription(controlName As String, eventName As String, targetName As String, Optional recursiveSearch As Boolean = False) If controlName = [String].Empty Then Throw New ArgumentNullException("controlName") End If If eventName = [String].Empty Then Throw New ArgumentNullException("eventName") End If If targetName = [String].Empty Then Throw New ArgumentNullException("targetName") End If Try Dim eventMethod = [GetType]().GetMethod(targetName) Dim control = Controls.Find(controlName, False).FirstOrDefault() If control IsNot Nothing Then Dim eventToSubscribe = control.[GetType]().GetEvent(eventName) Dim handler = [Delegate].CreateDelegate(eventToSubscribe.EventHandlerType, Me, eventMethod) Dim button = Controls.Find(controlName, recursiveSearch).FirstOrDefault() eventToSubscribe.AddEventHandler(button, handler) End If 'handle the exception your way Catch ex As Exception End Try End Sub
In order to make this snippet work, you need to ensure that the target method is accessible via reflection. If you use .net 3.5 or lower, remove the optional parameter from the method signature.
Was this snippet helpful? Do you know a better way to do this? Feel free to post a comment!
RT @CodeSnippetsNET: Dynamic Event Subscription using C# or #VB .NET http://t.co/JIY6BwrnGR #dotnet #csharp #visualstudio #visualbasic #cod…
RT @CodeSnippetsNET: Dynamic Event Subscription using C# or #VB .NET http://t.co/JIY6BwrnGR #dotnet #csharp #visualstudio #visualbasic #cod…
RT @CodeSnippetsNET: Dynamic Event Subscription using C# or #VB .NET http://t.co/JIY6BwrnGR #dotnet #csharp #visualstudio #visualbasic #cod…