Search code examples
c#winformsmdichildmdiparent

How I open a form at a time under MDI parent form?


I have a MDI form. Within this MDI there is multiple button to open new forms. Let buttons are btn1, btn2, btn3, btn4.... When I press btn1, form1 is load. when I press btn2, form2 is load... Now I press btn1, And form1 is loaded. If I press again btn1 then another form1 is open. Simultaneously let form1 is open, if I press btn2 form2 is open. But I want to open a form at a time. How I prevent this?


Solution

  • all the answers you got are good so i'm not going to repeat them, just give you an example of the member and method you can use to prevent that from happening:

      private Form frm;
    
      private void button1_Clicked(object sender, EventArgs e)
      {
         if (frm != null)
         {
            frm.Close();
            frm.Dispose();
         }
    
         frm = new Form1();
         frm.Show();
      }
    
      private void button2_Clicked(object sender, EventArgs e)
      {
         if (frm != null)
         {
            frm.Close();
            frm.Dispose();
         }
    
         frm = new Form2();
         frm.Show();
      }