C# Make Form1 Do An Action After Form2 is Closed

2020-08-02 19:35发布

问题:

I'm new to C# and I've been reading documentation and old questions, but I can't find figure out how to do the following.

I have two forms, Form1 and Form2.

Form1 contains a datagridview with content from a file. A button on Form1 opens Form2, where the user can enter information in textboxes. The user then clicks a button on Form2 which adds the new content to the file. This all works fine.

Now, there's an exit button on Form2. What I want is that when the user exits Form2, Form1 will immediately call the method to reload the datagridview so it's updated. How do I call this method automatically when Form2 is closed?

Thank you, your help is greatly appreciated!

回答1:

If the user doesn't have to interact with Form1 while Form2 is open, then show the second form as a modal dialog, which stops execution of the code in the first form, and just update your grid after displaying the second form.

using (var newFrm = new Form2())
{
    newFrm.ShowDialog();  // execution of Form1 stops until Form2 is closed
}

// read the file and update the DataGridView (this line executes when Form2 is closed)

Alternatively, you could subscribe to Form2's Closed event to execute code when it's closed:

var newFrm = new Form2();
newFrm.Closed += delegate
    {
        // read from file and update DataGridView
    };
newFrm.Show();


标签: c#