1

I'm trying to load usercontrols on button click, but problem is that, it disappears on postback inside user control.

this is how i load controls:

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 Answers 2

4

You need to reload the control when the page is post back. For example,

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);
}
Sign up to request clarification or add additional context in comments.

2 Comments

thx for help. but the problem is that i have menu like linkbuttons and i want to load different usercontrols on each click. if i load controls on each postback, they will all stay on screen. sorry for my bad English, hope you'll understand my post.
I answered similar question here stackoverflow.com/a/14449305/296861. If type of controls are mixed, you need to store SortedDictionary in ViewState instead of List<int>.
1

OF course it disappears, every request creates a brand new instance of your page and if you dont re-create the control on that postback then it wont exist.

See the following links about this very common issue.

Singing eels

Another SO question

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.