How to create controls dynamically in and retrieve values from it

Sometimes you may require to create controls dynamically in Because of page life cycle, you may loss the created controls on next post back(ASP.Net framework recreate the page on postback). You can resolve this issue by overriding LoadViewState() and SaveViewState() methods. LoadViewState() method restores view-state information from a previous page request that was saved by the SaveViewState method. This method will not executed on the first time. SaveViewState() method saves any server control view-state changes that have occurred since the time the page was posted back to the server. So in SaveViewState() method, store the values you wish to create. And in the LoadViewState() method, retrieve from the viewstate, which returned from SaveViewState() method.

Here is a sample implementation, in this text boxes are created based on the drop down list selection. In the SaveViewState() method, the value of the drop down list stored to the view state, and in the LoadViewState(), controls are recreated using the viewstate information.

private void CreateDynamicControls(int count)
    for (int i = 0; i < count; i++)
        var textBox = new TextBox();
        var textboxCell = new TableCell();
        var tableRow = new TableRow();

protected override object SaveViewState()
    var viewState = new object[2];
    //Saving the dropdownlist value to the View State
    viewState[0] = int.Parse(ddlRecipients.SelectedValue); ;
    viewState[1] = base.SaveViewState();
    return viewState;

protected override void LoadViewState(object savedState)
    //Getting the dropdown list value from view state.
    if (savedState is object[] && ((object[])savedState).Length == 2)
        var viewState = (object[])savedState;
        var count = int.Parse(viewState[0].ToString());

protected void cmdSubmit_Click(object sender, EventArgs e)
    //To get the textbox value, you can loop throw
    //the table cells and read the textbox controls
    foreach (TableRow row in tblRecipients.Rows)
        var textbox = row.Cells[0].Controls[0] as TextBox;

Happy Programming :)

You can find more information about LoadViewState() method and SaveViewState() method from MSDN.

Leave a Reply

Your email address will not be published. Required fields are marked *



You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>