Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Winforms user controls custom events

Tags:

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     } } 
like image 524
Kevin Avatar asked Feb 02 '10 22:02

Kevin


People also ask

What is event in user control in C#?

The registration for User Control events is typically done in the Page_Init method. Add this method to the User Control code. C# Copy. protected void Page_Init(object sender, EventArgs e) { } In Page_Init method, add registrations for the events to which your code should respond.

How do you make the events raised by child controls in a user control available to the host page?

By default, events raised by child controls in a user control are not available to the host page. However, you can define events for your user control and raise them so that the host page is notified of the event. You do this in the same way that you define events for any class.


1 Answers

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; }    } } 
like image 150
Ed S. Avatar answered Sep 20 '22 06:09

Ed S.