Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need to create an event handler for the button-event of the usercontrol and fire it from the click event of the actual button.</p> <pre><code>class MyControl : UserControl { public delegate void ButtonClickedEventHandler(object sender, EventArgs e); public event ButtonClickedEventHandler OnUserControlButtonClicked; } </code></pre> <p>Now you need to listen to the event of the actual button:</p> <pre><code>class MyControl : UserControl { // See above public MyControl() { _myButton.Click += new EventHandler(OnButtonClicked); } private void OnButtonClicked(object sender, EventArgs e) { // Delegate the event to the caller if (OnUserControlButtonClicked != null) OnUserControlButtonClicked(this, e); } } </code></pre> <p>From the main form (owner) you can now listen to the event:</p> <pre><code>public FancyForm : Form { public FancyForm() { _myUserControl.OnUserControlButtonClicked += new EventHandler(OnUCButtonClicked); } private void OnUCButtonClicked(object sender, EventArgs e) { // Handle event from here MessageBox.Show("Horray!"); } } </code></pre> <p><strong>Update</strong>: Both implementations can even safe a few lines of code by using Lambdas and default EventHandler delegate definitions.</p> <pre><code>class MyControl : UserControl { public event EventHandler OnUserControlButtonClicked; // Use this, if you want to use a different EventArgs implementation: // public event EventHandler&lt;CustomEventArgs&gt; OnUserControlButtonClicked; public MyControl() { _myButton.Click += (s, e) =&gt; { if (OnUserControlButtonClicked != null) OnUserControlButtonClicked(this, e); } } } public FancyForm : Form { public FancyForm() { _myUserControl.OnUserControlButtonClicked += (s, e) =&gt; MessageBox.Show("Horray!"); } } </code></pre> <p><strong>Update 2</strong>: Safe even more lines with the power of C# 6:</p> <pre><code>class MyControl : UserControl { public event EventHandler OnUserControlButtonClicked; public MyControl() { _myButton.Click += (s, e) =&gt; this.OnUserControlButtonClicked?.Invoke(this, e); } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload