简体   繁体   中英

How to get dynamically added UserControl and cast to the Interface implements

I have this code:

Control ctrl = Page.LoadControl("~/UserControls/ReportControl.ascx");
IReport rpt = (IReport)ctrl;
rpt.LoadData();
Panel.Controls.Add(ctrl);

So far everything is working as expected. Now I need on Button click postback event to get the loaded control and cast to the interface to use a method, and tried this:

if (Panel.Controls.Count > 0) {
   Control ctrl = Panel.Controls[0] as Control;
   IReport rpt = ctrl as IReport;
   string result = rpt.AMethodToInvoke();
}

This cast cannot happen and the control I get from the panel is a LiteralContol .

Any ideas? Thank you.

Have you got any other controls in your panel?

Maybe give your control an ID so

Control ctrl = Page.LoadControl("~/UserControls/ReportControl.ascx");
ctrl.ID = "UniqueID";
IReport rpt = (IReport)ctrl;
rpt.LoadData();
Panel.Controls.Add(ctrl);

And then user FindControl on the panel

Control ctrl = Panel.FindControl("UniqueID");

Also as you are adding the controls dynamically you need to make sure you are re-adding them on postback otherwise when you run the FindControl() it will return null.

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