-6

I have two forms, Form1 and Form2. Form1 is already open in the background and form2 is open above in showdialog().
I would like to call a method in Form1 from Form2 before closing it.
Here is my code:

// In the form1
form1  frm = (form1)Form.ActiveForm;
frm.AfterConnect();
Close();
Pio
  • 513
  • 4
  • 19

2 Answers2

1

You have to find the form and call the method, e.g.

using System.Linq;

...

Application.OpenForms
  .OfType<Form1>()     // Among the all opened forms of Form1 type 
  .LastOrDefault()     // Take the last one (or null if there's no such form)
 ?.AfterConnect();     // And call AfterConnect() on it (if the form has been found) 
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
  • If instead of calling the method found in Fom1, I would like to access a method in a Usercontrols ... How? – Carlos Kanika Nov 09 '17 at 20:33
  • If understand you right, you want to fire control's event (e.g. click a button - `MyButtonClick(object sender, EventArgs e) {...}`); if it's your case I suggest *extracting a method*, exposing it as a public one: `public void DoSomething() {...}` and call in the event handler: `MyButtonClick(object sender, EventArgs e) {DoSomething();}`. You still can call this exposed method with the code in the answer. – Dmitry Bychenko Nov 09 '17 at 20:46
0

You could create a property (of type Form1) in Form2. Then when opening Form2 from Form1 set the property. Now you can call any public methods in Form1 from Form2.