Reputation:
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
Reputation: 97
public class MyLabel:Label
{
public void PerformClick()
{
OnClick(new EventArgs());//InvokeOnClick(this,new EventArgs());
}
}
Upvotes: 0
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
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
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
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