Reputation: 2984
I'm using a user control (uc1) inside a Windows form (f1) in order to Display some of the elements of my form.
There (uc1) though I Need to Access a few elements of the form (f1). Thus I had the following line i the load:
private void UC1_Load(object Sender, EventArgs e)
{
F1 parentFrom = (F1)this.parent;
}
Now this works absolutely fine on execute BUT when I try to open F1 in the designer I get the error (Translation from my mother language):
The object of the type "System.Windows.Forms.Form" can not be transformed into the type "F1".
Thus I can't open it in the designer without ignoring this "error". My question here is thus am I doing something wrong or can I somehow avoid this error?
Upvotes: 1
Views: 31
Reputation: 48415
You can either check for null and only work with it if it's valid, which you should probably be doing anyway:
F1 parentFrom = this.parent as F1;
if(parentForm != null)
{
// Do something.
}
Or you can check LicenceManager.UsageMode
to see if the control is running in design mode:
if (LicenseManager.UsageMode != LicenseUsageMode.Designtime)
{
F1 parentFrom = (F1)this.parent;
}
Or why not even a mix of both.
As a side note, it seems to defeat the point of a user control if it can only be used directly on one specific form. Perhaps you do have a valid use case, or perhaps you should think about refactoring your approach. For example, if you want something to happen on the form when the user control is updated you could use a custom event and the form can take the appropriate action when the event is fired.
Upvotes: 2