ParentForm is null (in a Button inside a UserControl inside a Form)!

人盡茶涼 提交于 2019-12-24 09:36:07

问题


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 NULL!

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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/4871578/parentform-is-null-in-a-button-inside-a-usercontrol-inside-a-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!