title: WinForms: How to programmatically fire an event handler?
body: <p>I want to programmatically invoke an event handler for a control. For example:</p>
  
  <pre><code>DateTimePicker dtpLastConsummated;
  </code></pre>
  
  <p>I want to trigger the TextChanged event handler for the <code>dtpLastConsummated</code>, how can i do it?</p>
  
  <p>In other languages I would call something akin to:</p>
  
  <pre><code>dtpLastConsummated.TextChanged(this, new EventArgs());
  </code></pre>
  
  <p>but in .NET you can have multiple event handlers:</p>
  
  <pre><code>dtpLastConsummated.Click +=new EventHandler(dtpLastConsummated_TextChanged);
  dtpLastConsummated.Click +=new EventHandler(dtpLastConsummated_AnotherHandler);
  dtpLastConsummated.Click +=new EventHandler(dtpLastConsummated_MoreHandlers);
  ...
  dtpLastConsummated.Click +=new EventHandler(dtpLastConsummated_Nminus1);
  </code></pre>
  
  <p>so you need a way to trigger all the attached event handlers.</p>
  
  <hr>
  
  <h2>Answer</h2>
  
  <p>The following code will fire the event:</p>
  
  <pre><code>Toolkit.FireEvent(dtpLastConsummated, "TextChanged", new EventArgs());
  </code></pre>
  
  <p>And here's the code of the static toolkit function:</p>
  
  <pre><code>/// &lt;summary&gt;
  /// Programatically fire an event handler of an object
  /// &lt;/summary&gt;
  /// &lt;param name="targetObject"&gt;&lt;/param&gt;
  /// &lt;param name="eventName"&gt;&lt;/param&gt;
  /// &lt;param name="e"&gt;&lt;/param&gt;
  public static void FireEvent(Object targetObject, string eventName, EventArgs e)
  {
     /*
      * By convention event handlers are internally called by a protected
      * method called OnEventName
      * e.g.
      *     public event TextChanged
      * is triggered by
      *     protected void OnTextChanged
      * 
      * If the object didn't create an OnXxxx protected method,
      * then you're screwed. But your alternative was over override
      * the method and call it - so you'd be screwed the other way too.
      */
  
     //Event thrower method name //e.g. OnTextChanged
     String methodName = "On" + eventName;
  
     MethodInfo mi = targetObject.GetType().GetMethod(
           methodName, 
           BindingFlags.Instance | BindingFlags.NonPublic);
  
     if (mi == null)
        throw new ArgumentException("Cannot find event thrower named "+methodName);
  
     mi.Invoke(targetObject, new object[] { e });
  }
  </code></pre>
  
  <hr>
  
  <p><strong>Note:</strong> I'm not creating a subclass of every control in the .NET framework, and every 3rd party control, and convincing an enterprise worth of developers to retrofit every form to use my custom controls.</p>