Search code examples
c#winformsmodal-dialogdialogresult

DialogResult that doesn't close the form?


I have a form Form1 from which I display Form2 as a modal form. From Form2 I do all sort of editing and deleting of different set of values which should be reflected in Form1 after closing Form2. So what I do is RePopulateControls_in_Form1() after closing Form2. Since RePopulateControls_in_Form1()is a long process, I want to execute that method only if some modification (edit,add, delete) happens in Form2 and not when Form2 is just opened and closed.

So this is what I try to do in Form1:

        Form2 f = new Form2();
        if (f.ShowDialog(this) == DialogResult.Something)
            RePopulateControls_in_Form1()

And then in Form2 I do,

    private void bntEdit()
    {
        //If Edit?
        this.DialogResult = DialogResult.Something;
    }
    private void bntAdd()
    {
        //If Add?
        this.DialogResult = DialogResult.Something;
    }
    private void bntDelete()
    {
        //If Delete?
        this.DialogResult = DialogResult.Something;
    }

But my problem is .Something. If it is anything other than .None, Form2 simply gets closed. I do not want Form2 to get simply closed by its own unless the user closes it.

If I do this:

    //in Form1
    private void Form1_Click()
    {
        Form2 f = new Form2();
        if (f.ShowDialog(this) == DialogResult.None)
            RePopulateControls_in_Form1()
    }

    //in Form2
    private void Form2_SomeModification()
    {
        //If Modified?
        this.DialogResult = DialogResult.None;
    }

RePopulateControls_in_Form1() is not hit!

In short, in my program how can I tell the compiler to call RePopulateControls_in_Form1() only if values are modified in Form2?

Note: Repopulating is certainly required since the controls are dynamically created and a bit complex (actually what is created in Form2 is GUI controls and its labels etc).


Solution

  • Setting DialogResult on Form hides the form and returns from ShowDialog. If you want to delay that until the user performs some other action (such as closing the form) you should store that state as a member field and set DialogResult in a handler for Form.Closing.

    Also, if you do want to dismiss the modal form on a button press, you can use the Button.DialogResult property instead of making a Button.Click handler.