How can I execute a function that is in another form?

2

I have two forms, one of them I have:

namespace J13_Rouparia_CS
{
    public partial class frmMain : Form
    {
          public static int LocPesq; 
          public static string peqNume;
          public static string peqArti;

          public void UpdatePesquisa()
          {
              switch (LocPesq)
              {
                 case 1:
                     txtSRnum.Text = peqNume;
                     txtSRartigo.Text = peqArti;
                     break;
                 case 2:
                     txtELnum.Text = peqNume;
                     txtELartigo.Text = peqArti;
                     break;
                 case 3:
                     txtSLnum.Text = peqNume;
                     txtSLartigo.Text = peqArti;
                     break;
              }  
         }
    }
}

On the other I'd like to run UpdatePesquisa() , using frmMain.UpdatePesquisa() , but the UpdatePesquisa method does not appear in the list. How can I resolve this?

    
asked by anonymous 12.11.2018 / 23:08

2 answers

1

You need to have the variable of your form instantiated in the location you are calling the UpdateProgress() method.

Is your form already active? Otherwise, you will have to instantiate the variable and call the method:

frmMain fMain = new frmMain();
fMain.UpdatePesquisa();

If your form is already active, you have two options:

  • Send the main form as a parameter in the constructor of the class you will use:

    public partial class frmMain : Form {
       public frmMain(FormReferencia x) {…}
    }
    
  • Use the Application.OpenForms["<nome da classe>"] function:

    Form1 f1 = (Form1)Application.OpenForms["Form1"];
    
13.11.2018 / 11:07
0

Assuming you want to access form frmMain from another one evoked by this same Form , you can do the following:

frmMain

/// <summary>
/// Método localizado em "frmMain"
/// Criar uma nova instância do novo form
/// passando este como "Owner"
/// </summary>
void AbrirNovoForm()
{
    frmNovoForm frmNovoForm = new frmNovoForm();
    frmNovoForm.Show(this);
}

frmNovoForm

/// <summary>
/// Método localizado em "frmNovoForm"
/// Fazer cast do "Owner" para "frmMain" e evocar o método "UpdatePesquisa()"
/// </summary>
void UpdatePesquisa() => (Owner as frmMain).UpdatePesquisa();
    
14.11.2018 / 15:04