2012-07-30

How to retain values of dynamically created controls in asp.net

Dynamically generated controls are getting lost whenever a post back happens. There is actually no way to keep them persistent across post backs. What we can do is, store the dynamically created controls in session and restore them back from the session when a post back happens. Following example demonstrate how to store the dynamically generated controls in session and restore them back when a post back happens.

ASPX code

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="
http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
</head>
<body>
    <form id="form1" runat="server">
    <asp:TextBox ID="HowManyToGenerateTextBox" runat="server" Text="0"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Generate" OnClick="GenerateButton_Click" />
    <asp:Button ID="Button2" runat="server" Text="Calculate" OnClick="CalculateButton_Click" />
    <asp:Label ID="ResultLabel" runat="server" Text="Result"></asp:Label>
    <asp:Panel ID="Panel1" runat="server">
    </asp:Panel>
    </form>
</body>
</html>

In this example, you can enter value in the textbox so it will dynamically generate that number of textboxes when the Generate button clicks. And when the Calculate button clicks, it will sum up all the values entered in the dynamically created textboxes and display the result in Result Label. Following is the C# code behind

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void Page_Init(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                //Generate initial textboxes
                GenerateButton_Click(sender, e);
            }
        }

        protected void GenerateButton_Click(object sender, EventArgs e)
        {
            //Generate textboxes
            int z = int.Parse(HowManyToGenerateTextBox.Text);

            Panel1.Controls.Clear();

            for (int i = 0; i < z; i++)
            {
                TextBox s = new TextBox();
                s.Text = i.ToString();
                s.ID = "tb" + i.ToString();
                Session[s.ID] = s;
                Panel1.Controls.Add(s);
            }
        }

        protected void CalculateButton_Click(object sender, EventArgs e)
        {
            //Calculate sum
            int sum = 0;

            for (int i = 0; i < Session.Count; i++)
            {
                string textboxID = "tb"+i.ToString();
                TextBox checkIfTextBox = (TextBox)Session[textboxID];

                if (checkIfTextBox != null)
                    sum += int.Parse(checkIfTextBox.Text);
            }

            ResultLabel.Text = sum.ToString();
        }

    }
}

At the page load method, I’m calling to the Generate button click event to initialize the textboxes. In this case, since I’ve hardcoded value 0 to the HowManyToGenerateTextBox, it will not create any textboxes dynamically when the page loads. After that, you can enter any value to the textbox and click Generate button so it will create that number of textboxes. Now you can enter numbers to the dynamically created textboxes and click on the Calculate button. Now a post back happens. But I have stored the dynamically created textboxes in session so I can get them back from the session. I’m getting them back from session, sum it up and display the result in the Result label.

6 comments:

Anonymous said...

Thank you very much for this tutorial.

Melis Kathigitis said...

This adds the initial values in the textboxes rather than the user-inputed ones...

Ruchira Gamage said...

@Melis: That's correct.

mohd a said...

how to save the value from these textboxes in vb.net web forms...

mohd a said...

how to save the value from all these textboxes in database in vb.net

nilay sahu said...

@Melis : you're correct. How to get user-inputed values.???