Feature Post

Top

[Part 1/2] ASP.NET: Dynamic Controls

Quickest way to generate a control dynamically is four step process:

STEP 1: Add
STEP 2: Create
STEP 3: Draw/redraw
STEP 4: Read

STEP 1: Add manually a PlaceHolder control

Add on the ASPX page called phControls. Note that PlaceHolder control is used for easy identification of the dynamically added controls.


STEP 2: Create a TextBox control inside PlaceHolder

/// <summary>
    /// STEP1 : Draw controls
    /// </summary>
    private void DrawControls()
    {
        int nNumberOfControls = 4; //Could be dynamic, coming for a datasource?

        for (int i = 0; i < nNumberOfControls; i++)
        {
            TextBox tb = new TextBox();
            tb.Width = 155;
            tb.ID = "objControl" + i.ToString();//Notice objControl + i.ToString(), its important.

            phControls.Controls.Add(tb);

        }

        ViewState.Add("nNumberOfControls", nNumberOfControls);
    }

STEP 3: Redraw control inside PlaceHolder

/// <summary>
    /// STEP 2: Redraw controls
    /// </summary>
    private void RedrawControls()
    {
        int nNumberOfControls = int.Parse(ViewState["nNumberOfControls"].ToString());

        for (int i = 0; i < nNumberOfControls; i++)
        {
            //generate a new text box; replace with switch-case if the control
            //is of variable type.
            TextBox tb = new TextBox();
            tb.Width = 155; //set properties here.

            tb.ID = "objControl" + i.ToString(); //the dynamically generated object identifier
            phControls.Controls.Add(tb); //Add into PlaceHolder control
        }
    }

STEP 4: Read from control inside PlaceHolder

    /// <summary>
    /// STEP 3: Read text from controls
    /// </summary>
    private void ReadTextFromControls()
    {
        int nNumberOfControls = int.Parse(ViewState["nNumberOfControls"].ToString());

        for (int i = 0; i < nNumberOfControls; i++)
        {
            //Find textboxes in PlaceHolder, and cast as TextBox control
            TextBox ctl = this.Page.FindControl("objControl" + i.ToString()) as TextBox; 

            if (ctl != null)
                Response.Write(ctl.Text);
        }
    }

Usage:

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!Page.IsPostBack)
        {
            DrawControls();//First time, just draw
        }
        else
        {
            RedrawControls();//Other times, redraw existing controls.
        }
    }

You can call ReadTextFromControls() method on some button click event.