proper form Show()?

  • Thread starter Thread starter Flip
  • Start date Start date
F

Flip

I've seen one way of opening up another form in a C#/WinForms app and I had
done it another way and I would like to know what the gurus think is the
correct/better way?

I've seen one way, where the parent class/form instantiates the child form,
and still in the parent form, sets properties on the child form by calling
methods/properties on the child before before running a childForm.Show().

The way I had done it was to have a constructor in the child form that took
any/all properties/variables that I wanted to be set, then all I had to do
was instantiate the child form from the parent form and run a
childForm.Show().

What is the prefered way people do this kind of stuff in the real world?
Thanks.
 
I personally have always left the constructor alone and just used it to pass
in a reference to the parent form, and used properties across (set/get). I
find that it remains consistent throughout implementing many forms in your
application, more readable, and easier to follow. But in the world of OOP
as you know they say that variables that need to be set during the
initialization of the object should be done in the construction phase, but
only if they need to be initialized at that point. In the case of a form,
actually, your controls need to be set before they are "shown" but not
necessarily when the object is initializing. My 2 cents.

Alex
 
Flip,

For components, it's generally a bad idea to overload the constructor.
The reason for this is that the designer depends on a default constructor in
order to work. It also depends on public properties to allow you to set
values in the IDE as opposed to having to code them.

If it weren't for this case, I would say that it doesn't matter, but
having IDE integration is important, so I would stay that you stick with
this guideline.

Hope this helps.
 
Thank you Alex and Nicholas for your response. So it looks like the best
way to do it is via methods after the empty constructor is called.

Thanks again! :>
 
You can do it via methods but also in C# you can use properties, its very
handy, like so:

public TextBox tbFirstName;

public string FirstName
{
set
{
tbFirstName.Text = value;
}
get
{
return tbFirstName.Text;
}
}

In your main code:

Form1 form1 = new Form1(this);
form1.FirstName = "BlahBlahBlah";
form1.Show();
 
You can do it via methods but also in C# you can use properties, its very
handy, like so:
Thank you Alex. Yup, I was hoping that if I could access the form via
methods, I would get the properties for free, so thanks for confirming that
(I hadn't actually tried it yet). So it looks like that's the way to do it
then.
 
Back
Top