Click button call different methods

Asked

Viewed 1,688 times

2

I have a button that calls the click event btn_Salvar in my form.

How do I call this event different methods according to who created the form in which the button is contained?

EDIT:

Explaining better: I have the form "frmPrincipal", this "frmPrincipal" contains two menus, "productorRuralToolStripMenuItem" and "personFisicaToolStripMenuItem". The two call the same Form, but with some disabled controls. This btn_Salvar has to perform a method depending on the itemMenu that called it.

I believe that with IF ELSE I would solve the problem, however I want to avoid the use of IF ELSE as much as possible.

I am developing this application in layers: Accessodados, GUI, Negocios, Objetotransferencia. It would be correct for me to create a class within the GUI layer to solve this problem?

Follows code:

private void pessoaFisicaToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form frmCadPessoaFisica = new frmCadastroPessoas(new tipoFormPessoaFisica());
        frmCadPessoaFisica.MdiParent = this;
        frmCadPessoaFisica.Show();
    } 

    private void produtorRuralToolStripMenuItem_Click(object sender, EventArgs e)
    {
        Form frmCadPessoaProd = new frmCadastroPessoas(new tipoPessoaFormProdutor());
        frmCadPessoaProd.MdiParent = this;
        frmCadPessoaProd.Show();
    } 
  • Could explain better what you try to do with code examples?

  • according to who created the form - would not be you who created the form? You can give more details about your situation?

  • I made an Edit explaining better, thank you.

1 answer

2


Thus.

private void MyMethod(Form frm, MenuItem itemMenu)
{
    Form frmCadPessoaFisica = new frmCadastroPessoas(frm, itemMenu);
    frmCadPessoaFisica.MdiParent = this;
    frmCadPessoaFisica.Show();
}

private void pessoaFisicaToolStripMenuItem_Click(object sender, EventArgs e)
{
    MyMethod(new tipoFormPessoaFisica(), (MenuItem)sender);
} 

private void produtorRuralToolStripMenuItem_Click(object sender, EventArgs e)
{
    MyMethod(new tipoPessoaFormProdutor(), (MenuItem)sender);
} 

Inside your form you can do

// Ctor é o seu construtor e frm o seu parametro que passa por exemplo tipoFormPessoaFisica
// itemMenu é seu MenuItem (estou sem compilador por isso veja qual o tipo do objecto)

ctor(Form frm, MenuItem itemMenu) {
    // Aqui pode fazer o que quiser com o itemMenu como por exemplo itemMenu.Name ou itemMenu.Text
}
  • pho3nix, after the new form has been loaded, how to know within the new form what was the method that prompted it?

  • Solved. Thank you.

Browser other questions tagged

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