rigamonk rigamonk - 1 month ago 15
C# Question

User Control with multiple controls handle click

I have a User Control that has 3 labels on it. I would like the click event on the parent form to be raised when the control is clicked at any point on the canvas, even in the labels. Its like a button with 3 labels...right now it will only raise the parent event when the base canvas portion is clicked, but doestn't bubble up when the labels are clicked.
First, in the constructor I assign the event handlers:

public partial class RunCodeButton : UserControl
{
public event EventHandler ButtonClick;

public RunCodeButton()
{
InitializeComponent();
LblCode.Click += RunCodeButton_Click;
LblCount.Click += RunCodeButton_Click;
LblDescription.Click += RunCodeButton_Click;
}
}


Then I have the click event of the User control added to the class:

private void RunCodeButton_Click(object sender, EventArgs e)
{
ButtonClick?.Invoke(this, e);
}


then, in the main form (not the user control), i add the click event when I generate the button:

_button.Click += Button_Click;
private void Button_Click(object sender, EventArgs e)
{
Result = DialogResult.OK;
RunCode = (Codes_Run)((RunCodeButton)sender).Tag;
Close();
}


if i set a breakpoint inside the user controls click event, and click on a label. It raises the event, but 'ButtonClick' is always null and it stops there.

Is there a way to make the User controls child controls click event bubble up?

Answer

Add

_button.ButtonClick += Button_Click;

around the line

_button.Click += Button_Click;

Although you don't even need _button.ButtonClick. Simply do

private void RunCodeButton_Click(object sender, EventArgs e)
{
    Click?.Invoke(this, e);
}
Comments