C# Calling a method from another Form

2020-02-10 11:23发布

Hi I have 2 Form Form1 and Form2

Form1 have a table and there is my records and there is a Void for refresh the table in the Form1.

Form2 is my insert form I am insertig data to sqlserver.I wantto that When after i save the record in Form2 to run Form1 Refresh void.(when Form1,Form2 opened)

thanks.

4条回答
The star\"
2楼-- · 2020-02-10 11:51

Form2 will have to have a reference to the instance of Form1. You can pass this reference to Form2 when the insert button is clicked:

Form2 insertForm = new Form2();
//Form2.ShowDialog(Me); - Correction - 'Me' is for VB. in C# it's:
Form2.ShowDialog(this);

Next on Form2 you can access Form1 like this:

(Form1)this.Parent.RefreshTable();
查看更多
Anthone
3楼-- · 2020-02-10 11:54

In Form1, when you open Form2, attach to Form2 OnClose/Closed event, or a custom Save event, which when raised, refreshes the table in form 1.

查看更多
劳资没心,怎么记你
4楼-- · 2020-02-10 11:59

Adjust the construct for Form2 so it takes an extra parameter, like this:

...
private Form1 mainWindow;
public Form2(Form1 mainWindow)
{
   this.mainWindow = mainWindow;
}
...
public void HaveSavedSql()
{
   this.mainWindow.RefreshAll();
}

You should consider however looking up on Interfaces so you can seperate concerns. Interfaces are useful for many things!

查看更多
Luminary・发光体
5楼-- · 2020-02-10 12:12

try this to call method from another form :

if (System.Windows.Forms.Application.OpenForms["ParentFormName"] != null)
    {
        (System.Windows.Forms.Application.OpenForms["ParentFormName"] as   ParentFormName).MethodName(args);
    }
查看更多
登录 后发表回答