Victor
Victor

Reputation: 8480

Child elements events listener

On a C# Winform application. Imagine that I have a Panel with some labels inside.

How can I listen all click events from this labels in Panel click event?

Upvotes: 0

Views: 1267

Answers (3)

Evans
Evans

Reputation: 1599

If your Labels are children of the panel, a listener for the Click Event on the panel will listen all non redefined listeners of his children.

Example Code:

{ 
  //Form init
   panel1.Click += new System.EventHandler(this.panel1_Click);
  ....
}



private void panel1_Click(object sender, EventArgs e)
    {
        //The clicked label will be sender.
        Label l = (Label) sender; //Should be a safe cast. Will crash if sender is not a label

    }

Upvotes: 0

Parimal Raj
Parimal Raj

Reputation: 20585

Why not add a extra event handler to all the Control of Type Button within a Panel?

Sample Code :

    private void SetupButtonClickListenerForPanel1()
    {
        panel1.Click += ListenForAllButtonClickOnPanel1;
        foreach (Control control in panel1.Controls)
        {
            var tb = control as Button;
            if (tb != null)
            {
                tb.Click += ListenForAllButtonClickOnPanel1;
            }
        }

    }

    private void ListenForAllButtonClickOnPanel1(object sender, EventArgs eventArgs)
    {
        //
        Button tb = (Button) sender; // casting will fail if click is on Panel1 itself!
        MessageBox.Show(tb.Name);
    }

Linq way to add Handler :

    private void SetupButtonClickListenerForPanel1()
    {
        panel1.Click += ListenForAllButtonClickOnPanel1;
        foreach (var tb in panel1.Controls.OfType<Button>())
        {
            tb.Click += ListenForAllButtonClickOnPanel1;
        }
    }

Upvotes: 0

User 12345678
User 12345678

Reputation: 7804

You can do this programmatically by calling the following code in your Form_Load event handler or any other suitable event handler.

foreach (Label label in panel1.Controls.OfType<Label>())
{
    label.Click += LabelOnClick;
}

And then perform your operations in the event handler:

private void LabelOnClick(object sender, EventArgs eventArgs)
{
    MessageBox.Show("Label In Panel Clicked");
}

Upvotes: 1

Related Questions