user2626441
user2626441

Reputation:

How to perform Label click in C#?

I have a label working as a button. I would like when I press a button the click event to this label to take action. for example

private void Label1_Click(object sender, EventArgs e)
{
    MessageBox.Show("I pressed this label and showed me this messagebox");
}

Now I want when I press this button, the label1 click event to be performed

private void button1_Click(object sender, EventArgs e)
{
    // I want when I press this button something like this happens
    Label1.PerformClick();
}

Upvotes: 0

Views: 11701

Answers (5)

Huỳnh Hữu Ân
Huỳnh Hữu Ân

Reputation: 97

public class MyLabel:Label
{
    public void PerformClick()
    {
        OnClick(new EventArgs());//InvokeOnClick(this,new EventArgs());
    }
}

Upvotes: 0

MethodMan
MethodMan

Reputation: 18843

private void button1_Click(object sender, EventArgs e)
{
   Label1_Click(sender, e);
}

now if you want to show a message of which control was clicked all in one method do the following

private void label1_Click(object sender, EventArgs e)
{
    Control control = (Control)sender;
    var name = control.Name;
    MessageBox.Show(string.Format("I pressed this {0} and showed me this messagebox",name));
}

Upvotes: 5

Jmoreland91
Jmoreland91

Reputation: 178

I think it would be easier for you to just include the lable click functionality with the button click. Maybe even separate each piece in their own method and call them from the button click. Here is how you'd call another click event.

private void button1_Click(object sender, EventArgs e)
    {
        label1_Click(sender, e);
    }

Upvotes: 0

Mike Christensen
Mike Christensen

Reputation: 91618

Two ways to do this.

First:

private void button1_Click(object sender, EventArgs e)
{
   Label1_Click(sender, e); // Just call the Label's click handler
}

Second:

// Bind the Label1_Click handler to the button1 Click event, as they both use the same delegate
button1.Click += new EventHandler(Label1_Click); 

With the second approach, note that in C# delegates are multi-cast, so both the button1_Click handler and the Label1_Click handler will be called when the button is clicked, in the order they were bound.

Upvotes: 2

user2635745
user2635745

Reputation:

private void button1_Click(object sender, EventArgs e)
{
     //What the label click do:
      MessageBox.Show("I pressed this label and showed me this messagebox");
}

Is that not easier? Why do you want to do it ?

Upvotes: 0

Related Questions