Unable to cast object of type 'System.Windows.Forms.Form' to type 'Project.Form1'
I have a UserControl
that uses some of the public properties that I have available on my Form, at the top of the Paint
event for this UserControl
, I reference the Parent
of the control and cast it to the type of my Form.
var _parent = (Form1)Parent;
This code works h开发者_Python百科owever, in the Design view, an error is thrown and all I see in place of the UserControl
is a white box displaying the error in the title of this post. The stacktrace leads directly to this line of code.
Right now, I have fixed this error by re-routing this cast through a Property in my UserControl
public Form1 ControlParent
{
get
{
if (Parent != null)
{
return (Form1)Parent;
}
return null;
}
}
This is kind of a little much for something that just breaks the Design view.. any other ideas?
Based on the code it looks like your child Control
instance can already deal with ControlParent
being null
. Hence the simplest fix would be to just do the following
public Form1 ControlParent
{
get
{
return Parent as Form1;
}
}
Note: In general it's a bad idea to depend on the Parent
of a Control
being of a specific type. It prevents it from being re-hosted in other controls and can break designers which often fudge types around in order to provide a nice design experience. If you must depend on a value like Parent
being of a specific type make sure to have a fall back plan which doesn't crash in the face of a different type.
Did you check that parent is not null in first code?
You can try by setting form's owner and then accessing that property the way you are trying through the parent property.
精彩评论