MLyons10

I would like to set Form2 to open when Form1 initializes, but cannot seem to get this to work.

Here is the code I have:

public Form1()
{
InitializeComponent();
Form2 = new Form2();
form.Show();
}

How would I go about getting this to work The code above works to open Form2 on a button click, but apparently it needs to be different on initialize.

Any help and information is greatly appreciated.

Thanks,




Re: Visual C# Express Edition How to cause Form to open another form on initialize?

Traps

Why not try it in the Form1 Load event.



Re: Visual C# Express Edition How to cause Form to open another form on initialize?

MLyons10

Thanks, I will try that. What is the difference between Form Load and Form InitializeComponent They seem to me to be pretty much the same thing...

Thanks Again,





Re: Visual C# Express Edition How to cause Form to open another form on initialize?

IsshouFuuraibou

InitializeComponent/Constructor occurs when you do Form f = new Form();

Load occurs when you do f.Show(); or f.ShowDialog();

but also,
Form2 = new Form2();
form.Show();
is bad code, you should have something like
Form2 f2 = new Form2();
f2.Show();

Note the addition of f2 and the change of form to f2





Re: Visual C# Express Edition How to cause Form to open another form on initialize?

MLyons10

Thank you very much for the answer and the suggestion. If you don't mind, why is it bad code What does the inclusion of f2 do I'm very curious.

Thanks Again,




Re: Visual C# Express Edition How to cause Form to open another form on initialize?

IsshouFuuraibou

Form2 = new Form2() has a level of ambiguity. You shouldn't name variables the same as the class name, it means that when you reference Form2, you must know what scope you are in to know which you are using.

As for form.Show() in the next line, there is nothing that guarantees that it references your initialized Form2 from the code sample you gave.

adding f2 is the addition of a variable name, it allows "new Form2()" to actually reside in a specific location (that of f2) then you can reference f2. "f2" could have been anything (that's a legal variable name), I just choose f2 because it is simple. You could replace it with "myForm2" or something more descriptive





Re: Visual C# Express Edition How to cause Form to open another form on initialize?

MLyons10

Thank you very much for the explanation, that was very interesting. In the future I will definitely implement your method of calling new forms.

Thanks Again,