How To Create Dynamic Control Part-III

When working with dynamically created controls, you must add them back to the control tree early enough in the page life cycle to effectively participate in postback. Use the Init method on the page to create these controls. The controls will then manage events just as though they were placed on the page declaratively. Another challenge when working with controls dynamically is remembering information about the dynamic controls. Of course, the view state of the controls themselves will function similarly as static controls, but you might need information about which controls need to be created during postback. The dynamic controls must be created for the postback processing to handle the view state information they stored in the previous request. This post demonstrates creating a Textbox control during the initial request. We record the fact that the control was created in the page view state. We examine that stored information during the postback, which lets us know that we need to recreate that type of control so that it is part of the control tree and can handle the view state information that it saved previously.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="DynamicControl3.aspx.cs"
   Inherits="NamingContrainer" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
   <title>Untitled Page</title>
   <form id="theForm" runat="server">
           <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
           <asp:Panel ID="Panel1" runat="Server">
           <asp:Button ID="Button1" runat="server" type="Submit" Text="Go" />
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class NamingContrainer : System.Web.UI.Page

    protected void Page_Init(object o, EventArgs e)
        if (!IsPostBack)
            if (shouldCreateTextBox == true)

    protected override void LoadViewState(object savedState)
        if (savedState != null)
            object[] state = (object[])savedState;
            shouldCreateTextBox = (bool)state[1];
    protected override object SaveViewState()
        object[] state = new object[2];
        state[0] = base.SaveViewState();
        state[1] = shouldCreateTextBox;
        return state;

    private void CreateTextBox()

        for (int i = 1; i <= n; i++)
            TextBox t = new TextBox();
            t.ID = "TextBox" + i.ToString();
            HtmlGenericControl o = new HtmlGenericControl("br");

            shouldCreateTextBox = true;
    private static bool shouldCreateTextBox = false;
    private static int n = 1;

Next Post Previous Post
No Comment
Add Comment
comment url