Thursday, 12 May 2016

Adding Controls Dynamically - Persist Value in Dynamic Controls



public partial class Default2 : System.Web.UI.Page
{
    //private property to access the ControlsList in ViewState
    private List<string> ControlsList
    {
        get
        {
            if (ViewState["controls"] == null)
            {
                ViewState["controls"] = new List<string>();
            }

            return (List<string>)ViewState["controls"];
        }
    }
    private int NextID
    {
        get
        {
            return ControlsList.Count + 1;
        }
    }
    //LoadViewState fires before Page_Load but after OnPreInit
    protected override void LoadViewState(object savedState)
    {
        //MAKE SURE TO LEAVE THIS CALL TO THE BASE CLASS
        // this is what loads the ViewState into memory
        base.LoadViewState(savedState);

        foreach (string txtID in ControlsList)
        {
            TextBox txt = new TextBox();
            txt.ID = txtID;
            DynamicControlsHolder.Controls.Add(txt);
            DynamicControlsHolder.Controls.Add(new LiteralControl("<br>"));

        }

    }
 
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void btnOk_Click(object sender, EventArgs e)
    {
        TextBox txt = new TextBox();
        //assign a value to the ID of each control
        // so that each control can be uniquely identified
        txt.ID = "TextBox" + NextID.ToString();
        DynamicControlsHolder.Controls.Add(txt);
        DynamicControlsHolder.Controls.Add(new LiteralControl("<br>"));

        ControlsList.Add(txt.ID);
    }
}

No comments:

Post a Comment