ParentForm is null (in a Button inside a UserControl inside a Form)!
I got this code working!
I have a button inside a my UserControl dropped at design time in a my Form. All worked well and when in a button's event I called this.ParentForm it correctly returned to me the (only) parent Form.
After a refactoring, I moved the UserControl with the button to another NameSpace and the same piece of code no longer works. this.ParentForm now is NU开发者_StackOverflowLL!
I read the MSDN site and it says that only when the control is hosted in IE or another context this.ParentForm returns null. But I moved only the namespace!
Anyone has an idea?
I cannot use a different constructor to pass it the parent form because at design time Visual Studio wouldn't render the Form.
See if you're accessing the control's parent form before the control has been added to the form.
Your code my be triggering upon the user control class initialization, but the control hasn't been added to the Parent form.
Try putting this code in the Control Load event.
Look at the code-behind file that contains the designer-generated code. During the renaming, you may have confused the Visual Studio designer and it may have "orphaned" an instance of your control in the Form.designer.cs file.
In particular, look at the code in the InitializeComponent method and see if you can spot any code that creates an instance of your UserControl but does not add it to a container, or adds it to a container that is not added to the form.
精彩评论