How to trigger an event from one form in another

4

I am working with 2 forms, of which the first one acts as a floating box to collect data that is entered by the user. Once the data is entered, the user presses the Aplicar button to send the collected data to the second form, I want an event to be triggered in the second class.

In the first form I have this:

    public event EventHandler Aplicar;

    public void InvocarAplicar()
    {
        this.Aplicar?.Invoke(this, EventArgs.Empty);
    }

    public void Aplicar_Click(object sender, EventArgs e)
    {
        InvocarAplicar();  
    }

An event Aplicar that I want to trigger in the second form class:

private Form1 form1 = new Form1();

private void Form2_Load(object sender, EventArgs ev)
{
    form1.Aplicar += (s, e) =>
    {
        MessageBox.Show("Funciona");
    };
}

The problem is that it does not work, when I click on the button Aplicar of the first, the MessageBox that is in the class of the second is not displayed.

If I do it like this:

private void Form2_Load(object sender, EventArgs ev)
{
    form1.Aplicar += (s, e) =>
    {
        MessageBox.Show("Funciona");
    };
    form1.InvocarAplicar(); //Llamando diretamente
}

Then it does work, but I need the MessageBox that is in the class of Form2 to be displayed only when you click on the button Aplicar of Form1 .

What I need is to trigger an event in another form from a button.

Can someone tell me what I'm doing wrong?

Update:

  

Have you noticed that if you call, for example, Form1.Paint or Form1.Disposing or any predefined event, since Form2 , it will be executed?

     

There should be a way for the same thing to happen with the events that we define ourselves.

    
asked by Héctor Manuel Martinez Durán 23.04.2018 в 07:30
source

1 answer

4

Edit : As it has been solved in the comments of this answer, I updated it so that it has more visibility. As indicated by the partner @Pikoh and a server, in the end the error is in this line:

private Form1 form1 = new Form1();

When creating a new instance of Form1 instead of using the existing one, we are creating a new form different from the one we already had, therefore the event Aplicar will never be reached from the Form2.

To solve this, @Pikoh recommends passing as a parameter the instance of Form1 to Form2 and assigning Form1 in the constructor:

Form2 form2 = new Form2(this);

Where this is the current reference of Form1 that we are using.

    
answered by 23.04.2018 / 11:41
source