Buttons and Scopes of Forms

  • Thread starter Thread starter Patrick De Ridder
  • Start date Start date
P

Patrick De Ridder

Button1 displays Form1. Button 2 displays Form2. etc.

The changes are brought about by Buttoin_Clicks. How do I get rid of
Form1 purely by pressing Button2? Because as soon as I press Button2,
I have lost the scope of Form1 and I can no longer do Form1.Close();

(Of course I can get rid of Form1 by pressing the "X-Button" I have
put on Form1, but that is not what I want, I want Form1 to disappear
as soon as soon as I press Button2.)

Can it be done I wonder? How?

Thanks.
 
I am assuming you have a controlling FormParent that has your buttons. You
should use an instance variable to hold the currently allocated form. If
one is allocated your Click handlers can in turn close it out. It might
look something like this:

// instance variables for FormParent
private Button button1 = new Button();
private Button button2 = new Button();
private Form activeForm = null;

// Inside IntializeComponent or constructor
button1.Click += new EventHandler(this.OpenForm);
button2.Click += new EventHandler(this.OpenForm);

private void OpenForm(object sender, EventArgs e) {
if ( activeForm != null ) {
activeForm.Close();
activeForm = null;
}

if ( sender == button1 ) { activeForm = new Form1();
activeForm.Show(); }
else if ( sender == button2 ) { activeForm = new Form2();
activeForm.Show(); }
}
 
I am assuming you have a controlling FormParent that has your buttons.

Yes, that is what I have.
You should use an instance variable to hold the currently allocated
form. If one is allocated your Click handlers can in turn close it out.

Great, thanks a lot, I'll try and implement your suggestion.
 
I am assuming you have a controlling FormParent that has your buttons.
You should use an instance variable to hold the currently allocated
form. If one is allocated your Click handlers can in turn close it out.

It works truly fantastic. I have got the colors of the buttons
changing as well:) Thank you again.
 
Back
Top