Winforms user controls user events

Is there a way to provide User Control user events and trigger an event in an event in a user control. (I'm not sure invoke is the right term)

public partial class Sample: UserControl { public Sample() { InitializeComponent(); } private void TextBox_Validated(object sender, EventArgs e) { // invoke UserControl event here } } 

And 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 } } 
+21
c # event-handling winforms user-controls
Feb 02 2018-10-02T00
source share
2 answers

In addition to the example posted by Steve, there is also syntax that can simply go through an event. This is similar to creating a property:

 class MyUserControl : UserControl { public event EventHandler TextBoxValidated { add { textBox1.Validated += value; } remove { textBox1.Validated -= value; } } } 
+29
Feb 02 2018-10-02T00
source share

I believe you want 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 in 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 } } 
+27
Feb 02 2018-10-02T00
source share



All Articles