views:

455

answers:

3

I want to create a bunch of forms that all have the same properties and initialize the properties in the forms constructor by assigning the constructor's parameters.

I tried creating a class that inherits from form and then having all of my forms inherit from that class, but I think since I couldn't call InitializeComponent(), that I was having some problems.

Can someone post some c# code on how to do this?

+3  A: 

The parent's InitializeComponent should be called by having your constructor call base() like this:

public YourFormName() : base()
{
    // ...
}

(Your parent Form should have a call to InitializeComponent in its constructor. You didn't take that out, did you?)

However, the road you're going down isn't one that will play nicely with the designer, as you aren't going to be able to get it to instantiate your form at design time with those parameters (you'll have to provide a parameterless constructor for it to work). You'll also run into issues where it assigns parent properties for a second time, or assigns them to be different from what you might have wanted if you use your parametered constructor in code.

Stick with just having the properties on the form rather than using a constructor with parameters. For Forms, you'll have yourself a headache.

Adam Robinson
I agree, the designer does not support inheritance well. I had numerous problems with forms / controls that inherited from one another. The designer sometimes would crash, and if you had an error in one of the base classes, I would frequently need to blow away my existing form(s) and revert to a previous version. though it seems elegant, it ended up being far too more trouble than it was worth.
MedicineMan
A: 

An alternate pattern from inheritance here would be to use a factory to create the forms. This way your factory can set all the properties

JoshBerke
Code sample, please?
Ronnie Overby
A: 

Create an interface and pass that into the constructor of the form.

interface IFormInterface
{
      //Define Properties here
}

public MyForm(IFormInterface AClass)
{
      //Set Properties here using AClass
}

Though I'm usually doing more than just setting properties when I want to do something like this, so I end up creating an abstract class for default behaviors.

JupiterP5