2013-01-22 55 views
1

我想加载按钮点击usercontrols,但问题是,它在用户控制回发内消失。按钮点击动态加载用户控件,回发问题

这是我如何加载控件:

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(); 
} 

回答

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); 
} 
+0

THX的帮助。但问题是,我有菜单like linkbuttons,我想加载不同的usercontrols每次点击。如果我在每次回发时加载控件,它们都将保留在屏幕上。对不起我的英文不好,希望你能理解我的帖子。 – Mandragorasprout

+0

我在这里回答了类似的问题http://stackoverflow.com/a/14449305/296861。如果控件的类型是混合的,则需要在ViewState中存储SortedDictionary,而不是列表。 – Win

1

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

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

Singing eels

Another SO question