calling a event handler within another event handler?
25,548
Solution 1
You can do that - although the code you provide can't be compiled. It should look like this:
private void txtbox1_DoubleClick(object sender, EventArgs e)
{
button1_Click(sender, e);
}
private void button1_Click(object sender, EventArgs e)
{
MessageBox.Show(txtbox1.Text);
}
But for best practice and code readability, you're probably better off doing this, especially as you are not making use of sender
and e
:
private void txtbox1_DoubleClick(object sender, EventArgs e)
{
ShowMessageBox();
}
private void button1_Click(object sender, EventArgs e)
{
ShowMessageBox();
}
private void ShowMessageBox()
{
MessageBox.Show(txtbox1.Text);
}
Solution 2
Yes you can do that; an event handler is just another method.
However it might be worth creating a new method that shows the message box, and having both Click event handlers call that:
private void txtbox1_DoubleClick(object sender, EventArgs e)
{
ShowTextboxMessage();
}
private void button1_Click(object sender, EventArgs e)
{
ShowTextboxMessage();
}
private void ShowTextboxMessage()
{
MessageBox.Show(txtbox1.Text);
}
Solution 3
An event handler is nothing more than a method, so you can call it like any other.
Author by
woodykiddy
Updated on August 25, 2020Comments
-
woodykiddy over 3 years
Here is the short sample code:
private void txtbox1_DoubleClick(object sender, EventArgs e) { button1_Click(object sender, EventArgs e); //can I call button1 event handler? } private void button1_Click(object sender, EventArgs e) { MessageBox.Show(txtbox1.Text); }
I wonder if it would be okay to code in the above way?
-
woodykiddy over 12 yearsHmm looks better in the way you put it. But any "side-effects" if I use nested event handling? I guess it's just more or less a bit confusing.
-
George Duckett over 12 yearsNo side-effects, you're just calling a method like any other really.
-
woodykiddy over 12 yearshmm, are
sender
ande
used in both event handlers referencing the same thing? -
Roy Goode over 12 years@woodykiddy no - the sender for txtbox1_DoubleClick is txtbox1 and the sender for button1_Click will be button1 if the event handlers have been wired as standard using the Windows Form Designer