I have a custom usercontrol and I want to do something relatively simple.
When ever a numeric up down in that usercontrol's value changes, have the main form update a display window.
This is not a problem if the NUD was not in a usercontrol but I can't seem to figure out how to have the event handled by the mainform and not the usercontrol.
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.
From the Class Name drop-down list at the top of the Code Editor, select the object that you want to create an event handler for. From the Method Name drop-down list at the top of the Code Editor, select the event. Visual Studio creates the event handler and moves the insertion point to the newly created event handler.
In general, an event handler has the name of the event, preceded by "on." For example, the event handler for the Focus event is onFocus. Many objects also have methods that emulate events. For example, button has a click method that emulates the button being clicked.
You need to create an event handler for the user control that is raised when an event from within the user control is fired. This will allow you to bubble the event up the chain so you can handle the event from the form.
When clicking Button1
on the UserControl, i'll fire Button1_Click
which triggers UserControl_ButtonClick
on the form:
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); }
Form:
UserControl1.ButtonClick += new EventHandler(UserControl_ButtonClick); protected void UserControl_ButtonClick(object sender, EventArgs e) { //handle the event }
Notes:
Newer Visual Studio versions suggest that instead of if (this.ButtonClick!= null) this.ButtonClick(this, e);
you can use ButtonClick?.Invoke(this, e);
, which does essentially the same, but is shorter.
The Browsable
attribute makes the event visible in Visual Studio's designer (events view), Category
shows it in the "Action" category, and Description
provides a description for it. You can omit these attributes completely, but making it available to the designer it is much more comfortable, since VS handles it for you.
Try mapping it. Try placing this code in your UserControl
:
public event EventHandler ValueChanged { add { numericUpDown1.ValueChanged += value; } remove { numericUpDown1.ValueChanged -= value; } }
then your UserControl
will have the ValueChanged
event you normally see with the NumericUpDown
control.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With