andree
andree

Reputation: 3224

Inherit from a 'Form' which has parameters

I have a Form named ScanFolder, and I need another Form, that needs to be very similar to ScanFolder, so I decided to use form inheritance. But there seems to be some misunderstanding with the constructor.

ScanFolder looks like:

public partial class ScanFolder : Form
{
    public ScanFolder(MainForm parent, bool[] autoModes, GlobalMethods GMethodsClass)
    {
        //Doing something with parameters
    }
}

I tried to inherit Form like this:

public partial class Arch2 : ScanFolder
{
}

But I get warning Constructor on type 'mhmm.ScanFolder' not found, and also there is an error on Arch2 Form edit mode, where I see a call stack error.

So I tried something like this:

public partial class Arch2 : ScanFolder
{
    public Arch2(MainForm parent, bool[] autoModes, GlobalMethods GMethodsClass)
        : base(parent, autoModes, GMethodsClass)
    {
    }
}

But it is still the same.

As you can see, I clearly don't have any idea what I'm doing. What I'm trying to achieve is getting Arch2 to look the same as ScanFolder, so I can see it in designer view and also override some methods or event handlers.

Upvotes: 7

Views: 3820

Answers (2)

vgru
vgru

Reputation: 51204

To use the Forms designer, you will need to have a parameterless constructor:

public partial class ScanFolder : Form
{
    public ScanFolder()
    {
         InitializeComponent(); // added by VS
    }

    public ScanFolder(MainForm parent, bool[] autoModes, GlobalMethods gm)
       : this() // <-- important
    {
         // don't forget to call the parameterless ctor in each
         // of your ctor overloads
    }
}

Or, if you really need to have some init params, you can do it the other way around:

public partial class ScanFolder : Form
{
    public ScanFolder()
        : this(null, new bool[0], new GlobalMethods())
    {

    }

    public ScanFolder(MainForm parent, bool[] autoModes, GlobalMethods gm)
    {
        InitializeComponent(); // added by VS
        // other stuff
    }
}

I recommend the first approach, otherwise you need to pass some reasonable default parameters (I don't recommend passing a null parameter).

It seems that in some cases you will also have to restart Visual Studio after changing the class.

Upvotes: 14

Abbas Ghaf
Abbas Ghaf

Reputation: 11

You can use this code in parent form:

public partial class ScanFolder : Form
{
 public ScanFolder(MainForm parent, bool[] autoModes, GlobalMethods GMethodsClass)
  {
    //doing something with parameters
  }
}

and then in child form as:

public partial class ScanFolder : Form
{
  public ScanFolder(MainForm parent, bool[] autoModes, GlobalMethods GMethodsClass)
     : base(parent,autoModes,GMethodsClass)
  {
    //doing something with parameters
  }
}

Upvotes: 1

Related Questions