Invoking an event handler in another event handler?

Here is a short code example:

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 correct to code the code above?

+4
source share
3 answers

You can do this, although the code you provide cannot 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 are probably better off doing this, especially since you are not using 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); } 
+7
source

Yes, you can do it; an event handler is another method.

However, it might be worth creating a new method that displays the message box, and having both Click event handlers trigger this:

 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); } 
+4
source

An event handler is nothing but a method, so you can call it like any other.

+2
source

Source: https://habr.com/ru/post/1368912/


All Articles