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

BenTam 1,581 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

C#
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.
10,385 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Viorel 113K 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 (Microsoft) 4,742 Reputation points Microsoft Employee
    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