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

3

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

    
asked by anonymous 14.12.2017 / 17:35

1 answer

2

Modularize

Separate content from btnReabrirCaixa_Click into 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, so you do not need to separate the method. I would only do this if it made sense at that time the button to be clicked automatically.

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));
         }
    }
}

You can use it like this:

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

Same as Windows Forms.

Or call the method directly

Another way (I think it's ugly and may not apply in all cases, when the parameters are manipulated):

private void ValidarAberturaCaixa() {
    // ...
    btnReabrirCaixa_Click(null, null);
    // ...
}
    
15.12.2017 / 14:32