How is parentForm Reference null?

I have an application in which I added usercontrol to the form. When I check this.parentForm in the userControl constructor, it gives a null reference

My UserControl code is similar to

 public UserControl1() { InitializeComponent(); if (this.ParentForm != null)//ParentReference is null { MessageBox.Show("Hi");//Does Not get Called } } 
+4
source share
2 answers

When the control is created, it is not yet added to the form - therefore, of course, the parent form will be empty.

Even if you usually write it like:

 // Where form might be "this" form.Controls.Add(new UserControl1()); 

You should think of it as:

 UserControl1 tmp = new UserControl1(); form.Controls.Add(tmp); 

Now your constructor runs on the first line, but the first mention of form is on the second line ... so how can the control have any visibility?

You are likely to handle ParentChanged and take action accordingly. (Sorry if you are not using Windows Forms - I am sure there is an equivalent for other user interface interfaces, next time it would be useful if you could indicate what you are using in the question.)

+7
source

why did you add this line, do not really need to, delete this line

  if (this.ParentForm != null)//ParentReference is null public UserControl1() { InitializeComponent(); MessageBox.Show("Hi");//Does Not get Called } 
0
source

Source: https://habr.com/ru/post/982117/


All Articles