Unable to pass object of type "System.Windows.Forms.Form" to enter "Project.Form1"

I have a UserControl that uses some public properties that I have in my form, at the top of the Paint event for this UserControl , I refer to the Parent of the control and overlay this to the type of my Form.

 var _parent = (Form1)Parent; 

This code works, however, an error occurs in the Design view, and everything that I see instead of UserControl is a white frame that displays an error in the header of this message. A glass line leads directly to this line of code.

I have currently fixed this error by re-redirecting this action using the property in my UserControl

  public Form1 ControlParent { get { if (Parent != null) { return (Form1)Parent; } return null; } } 

It's a bit for something that just breaks the design view .. any other ideas?

+4
source share
3 answers

Based on the code, it looks like your child Control instance is already dealing with ControlParent being null . Therefore, the simplest solution would be to make the following

 public Form1 ControlParent { get { return Parent as Form1; } } 

Note. In general, a bad idea depends on Parent on Control on a particular type. This prevents re-placement in other controls and can break designers who often think of types around to provide a nice design. If you must depend on a Parent value of one type or another, make sure you have a return plan that does not reset in the face of another type.

+4
source

Have you verified that the parent does not have a null value in the first code?

0
source

You can try to set the owner of the form and then access this property the way you try to execute the parent property.

0
source

All Articles