[英]Pass variables and access methods of User Control from CodeBehind
So I have a function renderWidget()
in default.aspx.cs . 所以我在default.aspx.cs中有一个函数renderWidget()
。 The idea of this is to add a User Control to a page. 这样做的想法是将用户控件添加到页面。
public void renderWidget(string data) {
Control ctrl = Page.LoadControl("/widgets/widget.ascx");
dataPanel.Controls.Add(ctrl);
}
This all works fine, lovely jubbly. 这一切都很好,可爱多变。 Now in the other end, at the User Control, I have the following code in widget.ascx.cs : 现在在另一端,在用户控件中,我在widget.ascx.cs中包含以下代码:
public class WidgetControl : System.Web.UI.UserControl
{
public string testString = "";
public void test() {
Response.Write("test");
}
}
The problem arises when I try to access either of the properties in the User Control. 当我尝试访问用户控件中的任何一个属性时,就会出现问题。 When I try to add ctrl.test()
or ctrl.testString = "test"
to default.aspx.cs, I get the error "'System.Web.UI.Control' does not contain a definition for 'test'". 当我尝试将ctrl.test()
或ctrl.testString = "test"
到default.aspx.cs时,出现错误“'System.Web.UI.Control'不包含'test'的定义”。 I feel like there's probably something very basic I'm missing here. 我觉得这里可能缺少一些非常基本的东西。
Any help appreciated, thanks! 任何帮助表示赞赏,谢谢!
您需要将实例转换为WidgetControl
。
You have to cast to the correct type: 您必须强制转换为正确的类型:
WidgetControl widget = (WidgetControl)ctrl;
widget.testString = "Foo";
widget.test();
LoadControl
returns Control
and not the actual type of your UserControl
. LoadControl
返回Control
而不是UserControl
的实际类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.