Forms retaining values after closing

BlueRaja - Danny Pflughoeft picture BlueRaja - Danny Pflughoeft · Jan 4, 2011 · Viewed 7.5k times · Source

Throughout our program, forms are opened like this:

FormName.SomeValue = 10
FormName.ShowDialog()

rather than the usual

Dim myForm As New FormName
myForm.SomeValue = 10
myForm.ShowDialog()

(There is nothing we could do about this - this was done automatically by the Visual Studio VB6 --> VB.Net converter)

The problem is that when forms are closed, they seem to not really be closed, only hidden - if I add some text to a textbox and close/reopen the form, the text is still there, rather than the textbox being cleared like normal. This is presumably because the form always uses the same instance.

Is there any easy way to fix this other than going through the entire program and creating a new form instance for every ShowDialog() call (there are hundreds)?

We considered resetting every control in every form's Load event, but that would still be a pain, so we figured we'd ask if there's a simpler way first.

Answer

hungryMind picture hungryMind · Jan 4, 2011
public class MyForm: Form{

   private static MyForm myForm = null;

   public static DialogResult ShowDialog(bool newForm){
          if(newForm)
          {
                if(myForm != null) 
                    myForm.Dispose();
                myForm= new MyForm();
          }
          return myForm.ShowDialog();
   }

   public static DialogResult ShowDialog(){
          return ShowDialog(true);
   }
}