System.Windows.Forms.Control.Parent.get returned null

BenTam 1,801 Reputation points
2022-10-17T12:45:54.283+00:00

Dear All,

I get an error as follows. The codes of the application are shown below the screen capture.

  • Error *

250858-returnnull.gif

  • Call stack *

251095-callstack.gif

  • Code of ypanel *

251076-ypanel.gif

  • Solution Explorer *

251134-solutionexplorer.gif

Developer technologies | C#
Developer technologies | C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 125.7K Reputation points
    2022-10-17T14:06:24.27+00:00

    I think that the parent is not yet available because the control was not added yet to a form or control.

    Try executing the code inside the Load or ParentChanged event handlers.


  2. Lex Li 6,037 Reputation points
    2022-10-19T05:49:26.657+00:00

    When writing your code to read the value of .Parent, you should consider that null is a valid input, as documented by Microsoft in places such as

    https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.control.parent?view=windowsdesktop-7.0#remarks

    Setting .Parent to null explicitly has its meaning. And if you don't like that, you should assign whatever you like to .Parent when creating such UI controls.

    0 comments No comments

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.