close other form(C#).........

Hi...
I have two forms, Form A and Form B
two buttons in FormA(open button and colse button), I want to click the open button
then open the Form B , it is simple to do.... just like 
FormB thisForm = new FormB()
thisForm.Show();....

but I do'nt know how to close Form B from the Form A..


thanks..


Answer this question

close other form(C#).........

  • bobfidelman

    In formA do this...


    private void btnOpen_Click(object sender,EventArgs e)
    {
         thisFormB = new FormB();
         thisFormB.Show();
    }
    private void btnClose_Click(object sender,EventArgs e)
    {
         if(thisFormB != null && !thisFormB.Disposed)
         {
              thisFormB.Close();
              thisFormB.Dispose();
              thisFormB = null;
         }
    }

  • Chip Moody

    You need to keep a reference to the open FormB in FormA:

    FormB thisForm = null;

    // ...
    thisForm = new FormB();
    thisForm.Show();

    // ...
    thisForm.Close();

    Of course, you can open multiple instances of FormB like this, but the close button will only close the last one. And you have to check if FormB is open, so you don't try to close a window that's not open.

    If FormA isn't used until FormB closes, the easiest solution is .ShowDialog().

  • close other form(C#).........