The main object of this article is to access value of dynamic asp.net controls which are generated conditionally. For this, we will save viewstate of dynamic controls.
Suppose we have one dropdown and one button. When user selects “Generate” option, the Dynamic table will be generated. In each cell of table there will be textbox. User enters value in the textboxes and click on button then it will display all user entered values.

In aspx page:

<form id="form1" runat="server">
    <div>
        <asp:Table ID="tbl" runat="server">
        </asp:Table>
    <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" 
        onselectedindexchanged="DropDownList1_SelectedIndexChanged">
        <asp:ListItem>Select...</asp:ListItem>
        <asp:ListItem>Generate</asp:ListItem>
    </asp:DropDownList>
        <asp:Button ID="btnSet" runat="server" Text="Button" onclick="btnSet_Click" /> </div>
    </form>

To create dynamic control:


protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
    {
        if (DropDownList1.SelectedIndex == 1)
        {
            CreateDynamicTable();
        }
    }
private void CreateDynamicTable()
    {
       
        // Fetch the number of Rows and Columns for the table 
        // using the properties
        int tblRows = 5;
        int tblCols = 5;
        // Now iterate through the table and add your controls 
        for (int i = 0; i < tblRows; i++)
        {
            TableRow tr = new TableRow();
            for (int j = 0; j < tblCols; j++)
            {
                TableCell tc = new TableCell();
                TextBox txtBox = new TextBox();
                txtBox.ID = "txt-" + i.ToString() + "-" + j.ToString();  
                txtBox.Text = "RowNo:" + i + " " + "ColumnNo:" + " " + j;
                // Add the control to the TableCell
                tc.Controls.Add(txtBox);
                // Add the TableCell to the TableRow
                tr.Cells.Add(tc);
               
            }
            // Add the TableRow to the Table
            tbl.Rows.Add(tr);
            tbl.EnableViewState = true;
            ViewState["tbl"] = true;
        }      
    }

On Button click:


protected void btnSet_Click(object sender, EventArgs e)
    {
        foreach (TableRow tr in tbl.Controls )
        {
            foreach (TableCell tc in tr.Controls)
            {

                if (tc.Controls[0] is TextBox)
                { 
                    Response.Write(((TextBox)tc.Controls[0]).Text);         
                }
            }
            Response.Write("<br/>");  
        }
              
    }

Right Now, No output because dynamic controls are lost in postback then what to do.
So we need to save dynamic controls value and generate dynamic controls again.we need to maintain viewstate.


protected override object SaveViewState()
    {
        object[] newViewState = new object[2];

        List<string> txtValues = new List<string>();
                
        foreach (TableRow row in tbl.Controls)
        {
            foreach (TableCell cell in row.Controls)
            {
                if (cell.Controls[0] is TextBox)
                {
                    txtValues.Add(((TextBox)cell.Controls[0]).Text);
                }
            }
        }

        newViewState[0] = txtValues.ToArray(); 
        newViewState[1] = base.SaveViewState();
        return newViewState;
    }
protected override void LoadViewState(object savedState)
    {
        //if we can identify the custom view state as defined in the override for SaveViewState
        if (savedState is object[] && ((object[])savedState).Length == 2 && ((object[])savedState)[0] is string[] )
        {
           object[] newViewState = (object[])savedState;
            string[] txtValues = (string[])(newViewState[0]);
            if (txtValues.Length > 0)
            { 
                //re-load tables
                CreateDynamicTable();
                int i = 0;
                foreach (TableRow row in tbl.Controls)
                {
                    foreach (TableCell cell in row.Controls)
                    {
                        if (cell.Controls[0] is TextBox && i < txtValues.Length)
                        {
                            ((TextBox)cell.Controls[0]).Text = txtValues[i++].ToString();

                        }
                    }
                }
            }
            //load the ViewState normally
            base.LoadViewState(newViewState[1]);
        }
        else
        {
            base.LoadViewState(savedState);
        }
    }

Hurray.. Now you can access dynamic control value on button click.

Enjoy this.

Comments:  22

  • http://sirusbasevi.webs.com sirus

    It seems helpful, hope that it will help me because I am stuck on it.

  • Carl

    Thank you. I changed it to work for CheckBoxes as well. Worked like a charm

    I usually did a huge hack/workaround where I saved the values in hidden client side textboxes with javascript. this is so much better.

  • Satheeshmnair123

    where we need to call SaveViewState and LoadViewstate function???by adding the function,i am getting error when calling saveViewstate function before creating dynamic table..please help me

  • http://www.techbrij.com Brij Mohan

    No need to call
    See http://msdn.microsoft.com/en-u
    As you'll see on the diagram, LoadViewState for a control is called after the page's Init, and before the page's PreLoad; it is called only on postback, not on initial page load.

    A control's SaveViewState is called after the page's PreRenderComplete, but before the actual Render.

  • Kalai_7581

    I am creating dynamic textboxes and dropdown lists. I followed your code to Load and Save ViewStates, but my code is still not finding the dropdown list's selected values. However for textboxes, the code is finding the correct values stored in the textboxes. What is difference here? And what shouldI change/add in my code to get the ddl values. Thanks!

  • Kuiki

    Thanks!!

  • Krb

    Hi.. Thanks for the nice piece of code. But i still have a problem. I have the following code to create dynamic table
    protected void CreateDynamicTable()
    {
    for (int i = 1; i <= int.Parse(txtNoOfcase.Text); i++)
    {….}
    }
    But I am getting error for txtNoOfcase.Text. The text box has some text in it but it showing empty value. Note: the text box is not a dynamic textbox. Pls help.. Thanks..

  • Pallavi Kadiyala

    Hello Sir,
    I am getting an error as type or namespace name ”List”  could not be found………

    List txtValues = new List();

    plese help me in dis regard
    Thanks in advance

  • Robert Graauw

    This really helped me out. thnx for posting. 
    Greetings from Holland

  • neil the code monkey

    thanks for sharing – I’d tried about 3 or 4 different solutions and this work perfectly – good Karma to you my friend – thankyou

  • http://www.techbrij.com Brij Mohan

    Thanks neil for your comment

  • Sealsongs

    I struggled with saving the contents of dynamically generated text boxes, but your solution works great and seems like an elegant solution to a tricky problem. Thank you very much for sharing this!

  • divyansh singh

    Everything is working fine. Problem is not able to find the dropdown list’s selected values

  • George

    Fine piece of code, however, it doesn’t appear to allow the user to add values to the text boxes, it will only use the values entered in code:
    txtBox.Text = “RowNo:” + i + ” ” + “ColumnNo:” + ” ” + j;
    in the CreateDynamicTable method (or am I missing something?)
    George

  • Darani

    thanks a lot for useful example for dynamic controls

  • Dynamo

    Thanks a bunch buddy,,,, solution worked like a charm

  • swati tripathi

     i want to generate textboxes on dropdown selected index change and then enter values in textboxes and insert those values in database.

  • GeekIT

    Thanks a lot, god bless you, it seriously helps me

  • Irfan

    Yeah.. Really good a solution .. Liked it!
    Although didn’t use it yet. but seems fine..!!

  • http://profile.yahoo.com/UWV546KMHYDIDKEZ2YJUV7PMVI Sarah & Cameron B

    So first time it works fine, but when the user changed the drop down selection to say a 5th selection or 4th selection in the list, all the previous controls come back. How can I set it to return the new controls based on the new selection in the drop down list. Please help with that. Thanks.

  • Arash

    Thank you very much man.

  • Prajakta

    It is very useful. But i am using .net 2005 and i want to create text box dynamically and store values on submit. how to do this?