user3494389
user3494389

Reputation: 31

Displaying a non modal dialog in c# and getting a callback when the form is close

I have a User Control called MembersList which gives the user the ability to search for members and then the members who qualify based on search criteria are displayed in a grid. The user then can click an edit button or double click the row and then a modal member edit form is displayed. the user edits or views the member information and then closes the edit form and can search for another member. now i want to display the member edit form as non modal. Now i know i will call the Member Edit form with the Show method instead of the ShowDialog method. But how do I know when the user has closed the Member Edit form so the MembersList user control can re-display the grid to reflect any changes made in the edit form. How do i provide the Member Edit form with a callback method on the user control to call when the form is closed.

Upvotes: 2

Views: 4357

Answers (2)

Praveen Paulose
Praveen Paulose

Reputation: 5771

You can take multiple approaches here.

  1. Register an event to Form Closing and perform your actions of updating the grid within the Form Closing.

Stub code for Form Closing.

Form2 form = new Form2();
form.FormClosing += form_FormClosing;

void form_FormClosing(object sender, FormClosingEventArgs e)
{
    //Get the properties from the form and update your grid.
}

You will need to maintain properties in your Form2 to identify if the OK button was clicked or the Cancel button was clicked.

  1. Pass a delegate to the Form being opened and on button click call the delegate, which will update the grid.

  2. Have a custom event on Form2, subscribe to this event from the parent form and in the event handler update your grid.

  3. Have a public method in Form1 that can be called on the OK click of Form2

Upvotes: 2

Paolo Costa
Paolo Costa

Reputation: 1989

Here's a simplified solution

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 form = new Form2(this);
        form.Show();
    }

    internal void NotifyClosed(Form2 form2)
    {
         MessageBox.Show("Closed");
    }
}

public partial class Form2 : Form
{
    private Form1 _form1;
    public Form2(Form1 form1)
    {
        _form1 = form1;
        InitializeComponent();
    }

    private void Form2_FormClosed(object sender, FormClosedEventArgs e)
    {
        _form1.NotifyClosed(this);
    }

}

Upvotes: 0

Related Questions