Dynamic Event Subscription using C# or VB.NET

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!

Please rate this snippet

How to set a Property Value by Name in C# and VB.NET

To set a Property Value by Name in C# and VB.NET you can use the following snippet.

Sample C#

public static bool SetPropertyByName(this Object obj, string name, Object value)
{
	var prop = obj.GetType().GetProperty(name, BindingFlags.Public | BindingFlags.Instance);
	if (null == prop || !prop.CanWrite) return false;
	prop.SetValue(obj, value, null);
	return true;
}

Sample VB.NET

Public Shared Function SetPropertyValueByName(obj As [Object], name As String, value As [Object]) As Boolean
	Dim prop = obj.[GetType]().GetProperty(name, BindingFlags.[Public] Or BindingFlags.Instance)
	If prop Is Nothing OrElse Not prop.CanWrite Then
		Return False
	End If
	prop.SetValue(obj, value, Nothing)
	Return True
End Function

Please rate this snippet