2

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.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
robob
  • 1,739
  • 4
  • 26
  • 44

2 Answers2

5

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.

Kyle
  • 51
  • 1
  • 1
  • You identified the problem correctly, however the solution is a bit problematic: A Control does not have a Load event, only a Form has it.. (I have the same problem too, I cannot call this.Parent from the Ctor of an inherited button) – spaceman Jun 22 '18 at 06:22
2

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.

Josh
  • 68,005
  • 14
  • 144
  • 156
  • Best theory I think, there is no other decent explanation. – Hans Passant Feb 02 '11 at 07:24
  • Ok I resolved the problem and the solution was a little bit strange. In fact I set the value of a internal variable with the this.ParentForm in the "Costructor". This did not work. Then I deleted this one and directly used the this.ParentForm when I need. Now it works. – robob Feb 02 '11 at 19:11