Eutherpy
Eutherpy

Reputation: 4581

Windows Forms: wait until another form closes

I have a situation in which formA needs to update some data, but only after formB has closed. Is there a simple way to do this?

private void newProjectButton_Click(object sender, EventArgs e)
{
    NewProjectForm newProjectForm = new NewProjectForm();
    newProjectForm.Show();

    //wait for newProjectForm to close...

    DataTable dt = Util.ToDataTable(ProjectParticipantTable.GetUserProjectsDetails(Util.currentUserId));
    userProjectsDGV.DataSource = dt;
}

Upvotes: 1

Views: 3405

Answers (2)

tcwicks
tcwicks

Reputation: 505

If you don't want to use the modal showdialog mode you can also use this approach.

private void newProjectButton_Click(object sender, EventArgs e)
{
    NewProjectForm newProjectForm = new NewProjectForm();
    newProjectForm.FormClosed += NewProjectForm_FormClosed;
    newProjectForm.Show();
}

private void NewProjectForm_FormClosed(object sender, System.Windows.Forms.FormClosedEventArgs e)
{
    ////will run when new form is closed

    DataTable dt = Util.ToDataTable(ProjectParticipantTable.GetUserProjectsDetails(Util.currentUserId));
    userProjectsDGV.DataSource = dt;
}

If you want only a singleton then make the newProjectForm variable a static singleton.

Upvotes: 1

NicoRiff
NicoRiff

Reputation: 4883

You have to make use of ShowDialog() method, and managhe the DialogResult property. For doing that, you have to set the DialogResult set on some part of NewProjectForm, that can be done setting the property in a button, or simply setting it by code. That will fire the DialogResult to your parent form and close the Form

You can do that this way:

using(NewProjectForm newProjectForm = new NewProjectForm())
{
   if(newProjectForm.ShowDialog() == DialogResult.OK)
   {
       DataTable dt = Util.ToDataTable(ProjectParticipantTable.GetUserProjectsDetails(Util.currentUserId));
       userProjectsDGV.DataSource = dt;
   }
}

Upvotes: 3

Related Questions