11

I'm making an application in C# using windows forms, I want to completely swap out all the content in a windows form and replace it with something else. Is there any convenient way to do this?

Example: I have a menu, when I click "start" I want the menu to disappear and the game to start. I'm not using XNA or anything like that which is kind of the point of this whole project.

jlodenius
  • 829
  • 2
  • 13
  • 24
  • see the answer for this question: http://stackoverflow.com/questions/297526/what-is-the-best-way-to-clear-all-controls-on-a-form-c – 03Usr Nov 27 '12 at 13:08
  • See [this answer](http://stackoverflow.com/questions/6953487/remove-hide-tab-headerswitcher-of-c-sharp-tabcontrol/6954785#6954785) which uses a modified tab control. – Lii Feb 12 '15 at 17:35

2 Answers2

8

Use one Panel for each unique content set you want to switch. Hide all of the panels, except the initial one. Create a variable activePanel. Set activePanel to current shown panel (i.e. initial one).

When you need to switch, do the following:

activePanel.Visible = false;
activePanel = <Panel you want to open now>; //I mean the Control, not an ID or something.
activePanel.Visible = true;

Another approach is to dynamically remove and add Controls to the form, but this way you'll have to write a lot more code, hovewer, your application memory footprint should be lesser.

J0HN
  • 26,063
  • 5
  • 54
  • 85
5

This works for me: Adding all the controls like:

form.Controls.AddRange(Pages.ToArray());

Then activating the needed one with

form.Controls[i].BringToFront();
Chen-Tsu Lin
  • 22,876
  • 16
  • 53
  • 63
user2894667
  • 51
  • 1
  • 1