Tuesday, August 14, 2012

ASP.Net Dynamic controls missing after postback

Scenario:
One of the fresher on my team had trouble with dynamic controls. Controls were added during a button click and were missing from UI as soon as another button is clicked on the page ( basically any other post back happens )

Solution:
Actually its by design, once page post back happens , data is saved in viewstate for dynamic controls also but dynamic controls will not be repainted. You will have to recreate in Page_Init or Page_Load.Here's a small sample which works.

Code:

using System;
using System.Web.UI.WebControls;

namespace SKN.TestDynamicControl{   

public partial class _Default : System.Web.UI.Page    
{        public int controlCount
        {
            get
            {
                if (null != ViewState["controlcount"])
                {
                    return (int)ViewState["controlcount"];
                }
                else
                {
                    return 0;
                }
            }
            set
            {
                if (null != ViewState["controlcount"])
                {
                    ViewState["controlcount"] = value;
                }
                else
                {                    ViewState.Add("controlcount", value);
                }
            }
        }        
        protected void Page_Load(object sender, EventArgs e)
        {
            for (int i = 0; i < controlcount; i++)
            {
                TextBox txt = new TextBox();
                txt.ID = "txt" + i;
                txt.Text = "Text" + i;
                pnlPlace.Controls.Add(txt);
            }
        }
        
        protected void Button1_Click(object sender, EventArgs e)
        {
            controlcount = 5;
            for (int i = 0; i < controlcount; i++)
            {
                TextBox txt = new TextBox();
                txt.ID = "txt" + i;
                txt.Text = "Text" + i;
                pnlPlace.Controls.Add(txt);
            }
        }
        protected void btnAdd_Click(object sender, EventArgs e)       {            
            string values = string.Empty;
            foreach (var item in pnlPlace.Controls)
            {
               if (item is TextBox)
               {
                    values += "," + (item as TextBox).Text;
                }
            }
            Response.Write(values);
        }
    }
}

0 comments: