23

Is there a way to give a User Control custom events, and invoke the event on a event within the user control. (I'm not sure if invoke is the correct term)

public partial class Sample: UserControl
{
    public Sample()
    {
        InitializeComponent();
    }


    private void TextBox_Validated(object sender, EventArgs e)
    {
        // invoke UserControl event here
    }
}

And the MainForm:

public partial class MainForm : Form
{
    private Sample sampleUserControl = new Sample();

    public MainForm()
    {
        this.InitializeComponent();
        sampleUserControl.Click += new EventHandler(this.CustomEvent_Handler);
    }
    private void CustomEvent_Handler(object sender, EventArgs e)
    {
        // do stuff
    }
}
GEOCHET
  • 21,119
  • 15
  • 74
  • 98
Kevin
  • 3,574
  • 10
  • 38
  • 43
  • You might find this first answer to this question useful http://stackoverflow.com/questions/2151049/net-custom-event-organization-assistance – John Knoeller Feb 03 '10 at 00:20
  • possible duplicate of https://stackoverflow.com/questions/7880850/how-do-i-make-an-event-in-the-usercontrol-and-have-it-handled-in-the-main-form – Arun Prasad Jan 22 '19 at 11:30

2 Answers2

33

Aside from the example that Steve posted, there is also syntax available which can simply pass the event through. It is similar to creating a property:

class MyUserControl : UserControl
{
   public event EventHandler TextBoxValidated
   {
      add { textBox1.Validated += value; }
      remove { textBox1.Validated -= value; }
   }
}
Ed S.
  • 122,712
  • 22
  • 185
  • 265
30

I believe what you want is something like this:

public partial class Sample: UserControl
{
    public event EventHandler TextboxValidated;

    public Sample()
    {
        InitializeComponent();
    }


    private void TextBox_Validated(object sender, EventArgs e)
    {
        // invoke UserControl event here
        if (this.TextboxValidated != null) this.TextboxValidated(sender, e);
    }
}

And then on your form:

public partial class MainForm : Form
{
    private Sample sampleUserControl = new Sample();

    public MainForm()
    {
        this.InitializeComponent();
        sampleUserControl.TextboxValidated += new EventHandler(this.CustomEvent_Handler);
    }
    private void CustomEvent_Handler(object sender, EventArgs e)
    {
        // do stuff
    }
}
Almo
  • 15,538
  • 13
  • 67
  • 95
Steve Danner
  • 21,818
  • 7
  • 41
  • 51