C# 将值传递到动态加载的web用户控件

C# 将值传递到动态加载的web用户控件,c#,asp.net,.net,user-controls,C#,Asp.net,.net,User Controls,我有一个ASPX页面,在preinit上我检查要加载的用户控件 control = "~/templates/" + which + "/master.ascx"; 然后在pageload上,我加载该控件 Control userControl = Page.LoadControl(control); Page.Controls.Add(userControl); 如何将动态加载的用户控件从aspx传输到ascx 可以使用Page.Findcontrol(…)在父页面中获取控件 见:

我有一个ASPX页面,在preinit上我检查要加载的用户控件

 control = "~/templates/" + which + "/master.ascx";
然后在pageload上,我加载该控件

 Control userControl = Page.LoadControl(control);
 Page.Controls.Add(userControl);

如何将动态加载的用户控件从aspx传输到ascx

可以使用Page.Findcontrol(…)在父页面中获取控件

见:

只要确保在代码中设置了ID,就可以访问它了。比如:

Control userControl = Page.LoadControl(control);
userControl.ID = "ctlName";
Page.Controls.Add(userControl);

在您的控件类类型中,您需要为控件创建公共属性(如果要将数据传输到控件)


可以创建由所有自定义控件实现的接口。通过这种方式,您可以强制转换到该接口,并使用它通过该接口传递数据。考虑这个例子:

public interface ICustomControl
{
    string SomeProperty { get; set; }
}
。。。以及您的控件:

public class Control1 : Control, ICustomControl
{
    public string SomeProperty
    {
        get { return someControl.Text; }
        set { someControl.Text = value; }
    }

    // ...
}
现在,您可以这样做:

Control userControl = Page.LoadControl(control);
Page.Controls.Add(userControl);

if (userControl is ICustomControl)
{
    ICustomControl customControl = userControl as ICustomControl;
    customControl.SomeProperty = "Hello, world!";
}
Control userControl = Page.LoadControl(control);
Page.Controls.Add(userControl);

if (userControl is ICustomControl)
{
    ICustomControl customControl = userControl as ICustomControl;
    customControl.SomeProperty = "Hello, world!";
}