How do I make an Event in the Usercontrol and have it handled in the Main Form?
you can do like this.....the below example shows text box(user control) value changed
// Declare a delegate
public delegate void ValueChangedEventHandler(object sender, ValueChangedEventArgs e);
public partial class SampleUserControl : TextBox
{
public SampleUserControl()
{
InitializeComponent();
}
// Declare an event
public event ValueChangedEventHandler ValueChanged;
protected virtual void OnValueChanged(ValueChangedEventArgs e)
{
if (ValueChanged != null)
ValueChanged(this,e);
}
private void SampleUserControl_TextChanged(object sender, EventArgs e)
{
TextBox tb = (TextBox)sender;
int value;
if (!int.TryParse(tb.Text, out value))
value = 0;
// Raise the event
OnValueChanged( new ValueChangedEventArgs(value));
}
}
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 useButtonClick?.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, andDescription
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.