Dispose Modal WinForm Dialogs

By Fons Sonnemans, posted on
3142 Views

There is a difference in disposing Modal and Non-Modal forms. In a training I gave last week I noticed that even experienced developers didn't know that Modal Dialogs don't dispose automatically, Non-Modal do.

private void buttonShowNonModalForm ( object sender , System.EventArgs e){
   &nbspnew TestForm().Show();
}

privatevoidbuttonShowModalDialog(objectsender, System.EventArgs e){
   &nbspnew Form2().ShowDialog();
}

The solution to this problem is very simple by creating the Form instance within a using block. This will dispose the Form when it is closed.

private void buttonShowModalDialog ( object sender , System.EventArgs e){
   &nbspusing(TestForm f =new TestForm()){
   &nbsp   &nbspf.ShowDialog();
   &nbsp}
}

An alternative solution uses a try/finnaly. Personally I prefer the previous, it is easier to read and write.

private void buttonShowModalDialog ( object sender , System.EventArgs e){
   &nbspTestForm f =null;
   &nbsptry{
   &nbsp   &nbspf =new TestForm();
   &nbsp   &nbspf.ShowDialog();
   &nbsp}finally{
   &nbsp   &nbspif(f !=null){
   &nbsp   &nbsp   &nbspf.Dispose();
   &nbsp   &nbsp}
   &nbsp}
}

The following solution isn't correct. You might think it is, but it isn't. The Dispose will not be executed when an Exception is thrown from within the ShowDialog().

private void buttonShowModalDialog ( object sender , System.EventArgs e){
   &nbspTestForm f =new TestForm();
   &nbspf.ShowDialog();
   &nbspf.Dispose();
}

All postings/content on this blog are provided "AS IS" with no warranties, and confer no rights. All entries in this blog are my opinion and don't necessarily reflect the opinion of my employer or sponsors. The content on this site is licensed under a Creative Commons Attribution By license.

Leave a comment

Blog comments

0 responses