如果我以编程方式加载它,如何访问用户控件属性?

Pen*_*uen 0 .net c# asp.net user-controls

我以编程方式加载了我的用户控件(.ascx),如:LoadControl("~/Controls/mycontrol.ascx").直到今天,我添加了两个成员来控制我的一切:

public StuffType stuffType { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    switch (stuffType)
    {
        case CardType.A:
            FillGvStuff();
            break;
        case CardType.B:
            FillGvExStuff();
            break;
        default:
            break;
    }       
}
Run Code Online (Sandbox Code Playgroud)

我怎样才能访问StuffType?

我找到了一种解决方案.

dav*_*eps 5

我想你会做这样的事情:

MyControl ctrl = (MyControl)LoadControl("~/Controls.mycontrol.ascx");
ctrl.stuffType = ...;
// put control somehwere
Run Code Online (Sandbox Code Playgroud)

基本上,当你加载它时,将它分配给一个变量并将其转换为它的类型,然后你应该有权访问它的方法和属性

您可能还想将page_load事件移动到page_prerender中,以便在控件中发生page_load事件之前明确设置属性