[英]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: 现在,我需要在Button
单击postback事件,以获取已加载的控件,并将其强制转换为使用方法的接口,然后尝试以下操作:
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
. 这种转换不会发生,并且我从面板上获得的控件是LiteralContol
。
Any ideas? 有任何想法吗? Thank you. 谢谢。
Have you got any other controls in your panel? 面板中是否还有其他控件?
Maybe give your control an ID so 也许给您的控件一个ID,这样
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 然后在面板上使用FindControl
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. 同样,在动态添加控件时,需要确保在回发时重新添加控件,否则当您运行FindControl()时,它将返回null。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.