Click here to Skip to main content
15,298,916 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Hello,
I have a problem while i am self learning C#. Here it is.
On a windows form application i have 2 froms(Form1 and Form2) . I show the Form2 to open an Excel file and read some data and then upon clicking "ok" on Form2 i need to execute a function on form1 and form2 can be closed(Of course i do this by this.close()).
Kindly let me know how i can call functions in form1 from form2.
I need to do this because form1 has data which needs to be worked upon.
Posted
Updated 25-Jul-21 11:41am
Comments
Steven.Pinto2000 30-May-11 3:23am
   
Can you show a demo code ?

This is a popular question about form collaboration. The most robust way is implementation of appropriate interface by the form class.

For more details, please see my past answer:
How to copy all the items between listboxes in two forms[^]. See also other suggestions and discussion.

—SA
   
Hello,

You can also use delegate:

In Form2:

MIDL
public delegate void methodHandler();
public methodHandler OnRunMethod;


In OK Click event:
C#
if (OnRunMethod != null)
    OnRunMethod();

example:
C#
private void OK_Click(object sender, RoutedEventArgs e)
{
    if (OnRunMethod != null)
        OnRunMethod();
}


In Form1 (where you open Form2):

Form2 form2 = new Form2();
form2.OnRunMethod += new methodHandler(MyMethod);
form2.Show() // or ShowDialog()


and in Form1:
C#
private void MyMethod()
{
    //Do somethings
}


I think it's a perfect way because it can be called from Form2 and you can use both of Show() or ShowDialog().

Good luck.
   
v2
On Form1's event where you open Form2, follow this -

1. Create object for form
Form2 f = new Form2();
2. Use f.ShowDialog() to open the form
3. Do what you do in form2
4. Code the other stuff after f.ShowDialog() which would run after form2 is closed.
   
Comments
asjadazeez 30-May-11 3:28am
   
Nice and simple solution. I just overlooked "showdialog" Thanks man !
Prerak Patel 30-May-11 4:11am
   
You are welcome.
Shahin Khorshidnia 30-May-11 4:54am
   
+5 It works.
form1 Test= new form1()
Test.FUNCTIONNAME()
this.close()
   
v3
Comments
asjadazeez 30-May-11 3:30am
   
Thanks got it.
JustWorking 30-May-11 8:17am
   
Remember to 5 :)
Make this method public and pass a reference to Form1 to Form2 constructor (custom ShowDialog method/whatever). Calling one form methods from another is not good practice, though. If possible, move it to another place (mediator class, static class or something)
   
Pass a reference of Form1 into Form2.
Once you need to call Form1, simply call the appropriate Form method (a public method) and then just close Form2.
   

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900