Kristian
Kristian

Reputation: 1378

passing form to user control breaks designer

I have a user control (section1), that I need to pass reference to my main form (Form1). The problem is whenever I pass the form as a argument to constructor of section1, it breaks the designer and I get an error:

 Type 'M.section1' does not have a constructor with parameters of types Form.    

 The variable 's1' is either undeclared or was never assigned.  

Form1.Designer.cs

 this.s1 = new M.section1(this); // this is the line that causes the problem

section1.cs The user control

public partial class section1 : UserControl
{
    private Form1 f { get; set; }

    public section1(Form1 frm) // constructor 
    {
         f = frm;
    }
}

It's weird that even though when I open Form1 in designer, it gives me the error, it compiles fine and the reference actually works and I can access Form1 from the user control. Any suggestions? Thanks!

Upvotes: 0

Views: 324

Answers (2)

YK1
YK1

Reputation: 7622

Designer uses reflection to create instance of your control. Hence you need a default constructor - that's what its looking for.

public partial class section1 : UserControl
{
    private Form1 f { get; set; }

    public section1() // designer calls this
    {
        InitializeComponent(); //I hope you haven't forgotten this
    }

    public section1(Form1 frm) : this() //call default from here : at runtime
    {
         f = frm;
    }
}

Upvotes: 1

YoryeNathan
YoryeNathan

Reputation: 14522

The solution I always use is having a default constructor or adding a default null value to the frm parameter:

public section1(Form1 frm = null)
{
    f = frm;
}

You might need to add some null checks here and there.

Upvotes: 0

Related Questions