Reputation: 8624
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.
Upvotes: 1
Views: 1292
Reputation: 2344
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.
Upvotes: 1