简体   繁体   中英

Can't access the properties of user control

I have a user control in which I am adding another user control, I am adding the child user control like below,

  ucSubMenu menu = new ucSubMenu(this);
  pnBox.Controls.Add(menu);

In the child user control I have property procedure which will initialise the parent user control. So in the constructor of the child user control I am taking the parent user control object as below,

    private UserControl parentUserControl;

    public UserControl ParentUserControl
    {
        get { return parentUserControl; }
        set { parentUserControl = value; }
    }
 public ucSubMenu(UserControl uc)
    {
        InitializeComponent();
        switch (Sys.ToString(uc.GetType()))
        {
            case "ucReport1":
                ParentUserControl = uc as ucReport1;

                MessageBox.Show(Sys.ToString(parentUserControl.GetType()));


                ReportClass rc =    parentUserControl.reportBindingSource.Current as ReportClass;
                //menuBindingSource.DataSource = rc.ItemList;
                break;
        }
    }

I can't access the parent user controls public properties as in the constructor, ReportClass rc = parentUserControl.reportBindingSource.Current as ReportClass; //menuBindingSource.DataSource = rc.ItemList; ReportClass rc = parentUserControl.reportBindingSource.Current as ReportClass; //menuBindingSource.DataSource = rc.ItemList;

how can I access the properties of a parent user control from a child user control?

The object parentUserControl is declared with the type UserControl , so at compile time only the properties of that class are known. To use the properties of the 'actual' control that occurs at runtime you will need to do type casting, like this:

ucReport1 reportCtl = (ucReport1)parentUserControl;

Then reportCtl.reportBindingSource will compile (assuming that I used the right Type Cast above, otherwise use what is needed).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM