tags:

views:

1051

answers:

3

What's the best method to switch between forms in C# ?

Scenario: I want to click a button in a Form1, kill the existing Form1 and create Form2. How can I achieve this ?

I would much appreciate it, if someone could even compare the complexity of this task in Winforms vs WPF.

+1  A: 

Surely it's just a very straightforward matter of closing the current form, creating an instance of the new one, and showing it? The following code (under the Click event handler in your case) ought to work in WinForms or WPF.

this.Close();
(new Form2()).Show();

Am I missing something here perhaps?

Noldorin
where would you locate "(new Form2()).Show()" ? You wouldn't get to that code because you Form1 object would be already destroyed
Those two lines belong in the click event handler of the button. Just because the first line closes the current form, it doesn't execution of code just suddenly stops! Try it out, and then let us know if you're having problems.
Noldorin
+2  A: 

The easiest way to do this is to have a controlling function that opens both of the forms. When the button is clicked on the first form, close it and move onto the second form.

using (var form1 = new Form1() ) {
  form1.ShowDialog();
}
using (var form2 = new Form2()) {
  form2.ShowDialog();
}

The code for WPF is similar. The biggest difference is that WPF windows (and pretty much all classes as a rule) do not implement IDisposable and hence do not require the using statement.

var win1 = new Window1();
win1.ShowDialog();
var win2 = new Window2();
win2.ShowDialog();
JaredPar
Yes, this is a solution. What happens if I need to have 100 windows or even more ? I can't create all them and keep them in memory, and the make them visible when I need them.
A: 

this.Close(); (new Form2()).Show();

this on a button click doesn't work. It terminates your window before you can get into form 2

asd