Home >Backend Development >C++ >How Can I Pass Events from a User Control to Its Parent Form?
Passing Events Up the User Control Hierarchy
In custom user controls, it's often desirable to make events raised within the control accessible to the main form. This becomes evident when attempting to handle events that originate from subcontrols, such as value changes in a numeric up-down control.
Creating an Event Handler
To address this challenge, create an event handler within the user control that gets triggered when the desired event occurs. This event handler should "bubble up" the event to the form, enabling it to handle it.
Example Code
Consider a user control with a button named "Button1":
User Control:
[Browsable(true)] [Category("Action")] [Description("Invoked when user clicks button")] public event EventHandler ButtonClick; protected void Button1_Click(object sender, EventArgs e) { //bubble the event up to the parent if (this.ButtonClick!= null) this.ButtonClick(this, e); }
Main Form:
UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick); protected void UserControl_ButtonClick(object sender, EventArgs e) { //handle the event }
Notes
The above is the detailed content of How Can I Pass Events from a User Control to Its Parent Form?. For more information, please follow other related articles on the PHP Chinese website!