c#: Modal forms, ShowDialog and Close()

1 comment

In first form you want to show a modal form to user, and get some object/property back from it.

You create a new form and shows it using ShowDialog()

            frmTilbud frm = new frmTilbud(t)


            …. some more code after frm is closed here

How do you get the object back to the first form?

You of course have the Dialogresult, but that's just a simple Ok/Cancel etc.

You could call methods and set properties on the first form, but then you wouldn't want/need the modal dialog.

You should think that when closing the modal form, you would also loose any properties etc on the modal form.

But this is the clue and solution:

even calling this.Close()  in the modal form does not unload it from memory

That means you can create public properties on your modal form, and check them when it's closed again

            frmTilbud frm = new frmTilbud()


            if (frm.MyProperty != null)



This also means that you're modal dialog isn't disposed before you explicitly call dispose on it (or you exit your application)

So a good practice is this:

            using (frmTilbud frm = new frmTilbud())



            if (frm.MyProperty != null)

                  resultprop = frm.MyProperty;


This disposes the form when you're finished with the curly braces.



Posted via email from Henris blogg

1 comment :

  1. Thanks ! It's sort of 'basic stuff' but useful as we often can't see the forest for the trees...