how parentForm Reference is null?

前端 未结 2 656
一整个雨季
一整个雨季 2021-01-18 20:42

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

相关标签:
2条回答
  • 2021-01-18 21:29

    When the control is being created, it won't have been added to a form yet - so of course the parent form will be null.

    Even if you'd normally write it as:

    // 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 is being executed in the first line, but the first mention of form is in the second line... so how could the control have any visibility of it?

    You should probably be handling the ParentChanged event instead, and taking appropriate action then. (Apologies if you're not using Windows Forms - I'm sure there's an equivalent for other UI frameworks; next time it would be useful if you could state what you're using in the question.)

    0 讨论(0)
  • 2021-01-18 21:35

    for what did you added this line no need actually, remove this line

     if (this.ParentForm != null)//ParentReference is null
    
    public UserControl1()
            {
                InitializeComponent();            
                MessageBox.Show("Hi");//Does Not get Called
    
            }
    
    0 讨论(0)
提交回复
热议问题