Link to home
Start Free TrialLog in
Avatar of ThePATMAN26
ThePATMAN26Flag for United States of America

asked on

C# - Open/Close a form multiple times

Good morning,

New to C#. I've created a small program with an "about" menu item. When clicked the program opens another form. I want to code this so you can close and open this about forms as many times as one wishes. The way I have it coded, the about form will open and close once, but when you try and open it again it throws an error ("Can't access a disposed object").

As I am teaching myself, I feel a bit lost. What is the best way to open and close an additional form from some event in the main form as many times as one wishes?

A sample of the code I'm using:

private about af = new about();

private void dispAbout(object sender, EventArgs e)
{
af.StartPosition = FormStartPosition.CenterScreen;
af.MinimumSize = new Size(600,300);
af.show();
}
ASKER CERTIFIED SOLUTION
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ThePATMAN26

ASKER

Ah, I knew I was close to the mark. Didn't even think to give that a shot. Thank you very much.
The problem is that once you hit close (eg. the x at top right on the form) then it destroys the form - hence your error when you attempt to show it again.
(You want the form to be hidden not closed.)


Is there a particular reason you want to keep the form - user input for example.  If it is just to display the same information then don't try to keep the form, just create a new one as necessary.
ps.  The answer you accepted (whilst I was typing my comment) is only suitable in some circumstances.

eg.  Without closing this new form try to open it again a few times - is that what you want ?
I'd have to agree with Andy.  You probably didn't want multiple instances of your about available at the same time did you?

In addition to sedgwick's suggestion, I'd change Show() to ShowDialog():

    af.ShowDialog();

With your original approach, though, you can use a check like this if you need to leave the declaration of the form out at class level (which is desirable under certain circumstances):
        private about af = null;

        private void dispAbout(object sender, EventArgs e)
        {
            if (af == null || af.IsDisposed)
            {
                af = new about();
            }
            af.StartPosition = FormStartPosition.CenterScreen;
            af.MinimumSize = new Size(600, 300);
            af.Show();
        }

Open in new window