在按钮单击,回发问题上动态加载用户控件

时间:2013-01-22 14:56:34

标签: c# asp.net

我正在尝试在按钮点击时加载用户控件,但问题是,它会在用户控件内回发时消失。

这就是我加载控件的方式:

private bool IsUserControl
{
    get
    {
        if (ViewState["IsUserControl"] != null)
        {
            return (bool)ViewState["IsUserControl"];
        }
        else
        {
            return false;
        }
    }
    set
    {
        ViewState["IsUserControl"] = value;
    }
}


#region Usercontrols
private void CreateUserControlAllNews()
{
    Control featuredProduct = Page.LoadControl("path/usercontrol.ascx");
    plh1.Controls.Add(featuredProduct);
}

#endregion
protected void allNewsbtn_Click(object sender, EventArgs e)
{

    this.IsUserControl = true;
    if(IsUserControl)
    CreateUserControlAllNews();
}

2 个答案:

答案 0 :(得分:4)

您需要在回发页面时重新加载控件。例如,

protected void Page_Load(object sender, EventArgs e)
{
    if (IsUserControl)
    {
        CreateUserControlAllNews();        
    }
}

private void CreateUserControlAllNews()
{
    Control featuredProduct = Page.LoadControl("path/usercontrol.ascx");
    featuredProduct.ID = "1234";
    plh1.Controls.Add(featuredProduct);
}

答案 1 :(得分:1)

当然它会消失,每个请求都会创建一个全新的页面实例,如果你不在该回发上重新创建控件那么它就不会存在。

请参阅以下有关此常见问题的链接。

Singing eels

Another SO question