How to reuse the Click of a button event in another method?

Asked

Viewed 4,415 times

3

I have the event Click btnReabrirCaixa_Click and would like to reuse the process that has within that event in a method ValidarAberturaCaixa(), without copying and pasting the entire code, how could this be done?

  • 2

    plays the button code in a method, if not using the sender and calls the method inside the event, and inside the other method. If you want an example, provide one that we will change it

  • ASP MVC, Web Forms? What are you working with?

  • Related(duplicate ?): https://answall.com/q/215845/2541

1 answer

2


Modularize

Separate the contents of btnReabrirCaixa_Click in a method and call it in ValidarAberturaCaixa and btnReabrirCaixa_Click, as:

private void MetodoSeparado() {
    // ...
}

private void btnReabrirCaixa_Click(object sender, EventArgs e) {
    MetodoSeparado();
}

private void ValidarAberturaCaixa() {
    // ...
    MetodoSeparado();
    // ...
}

Or trigger the event

You can trigger the click event, then you wouldn’t need to separate the method. I would only do that if it made sense at that point the button be automatically clicked.

Windows Forms

private void ValidarAberturaCaixa() {
    // ...
    btnReabrirCaixa.PerformClick();
    // ...
}

WPF

private void ValidarAberturaCaixa() {
    // ...
    btnReabrirCaixa.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
    // ...
}

To be reusable and more organized, you can create an extension method in WPF:

namespace System.Windows.Controls
{
    public static class ButtonExtensions
    {
         public static void PerformClick(this Button obj)
         {
             obj.RaiseEvent(new RoutedEventArgs(Button.ClickEvent));
         }
    }
}

There you can use so:

private void ValidarAberturaCaixa() {
    // ...
    btnReabrirCaixa.PerformClick();
    // ...
}

Same as Windows Forms.

Or call the method directly

Another way (I find ugly and may not apply in all cases, when there is manipulation of the parameters):

private void ValidarAberturaCaixa() {
    // ...
    btnReabrirCaixa_Click(null, null);
    // ...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.