65.9K
CodeProject is changing. Read more.
Home

Dynamic Controls Explained

starIconstarIcon
emptyStarIcon
starIcon
emptyStarIconemptyStarIcon

2.33/5 (5 votes)

Aug 30, 2006

1 min read

viewsIcon

43960

downloadIcon

166

A simple explaination of a sometimes complicated topic

Sample Image - Dynamic_Controls.gif

Sample Image - Dynamic_Controls2.gif

Introduction

The sample is meant to convey an idea that doesn't get a lot of coverage on the web; creation of dynamic controls and how to make them work with ViewState.

Background

I never had a real need to learn much about dynamic controls until I started working on a project for a client that wanted some complex functionality that was very flexible.  As I tried to find help on how to accomplish my task I quickly realized that there was very little coverage of something so easy to achieve.  After I found the solution I decided to write this article so that others wouldn't have to work as hard as I did when faced with the same problem.

Using the code

This code shows how to add dynamic controls to a page and allow ViewState to do the rest.  The key to getting dynamic controls to work properly is to add the controls in the pages Init event since ViewState gets loaded on the pages Load event.  You must also make sure that the dynamic controls are re-created on every post-back.

    /// <summary>

    /// Override the page initialize event; this is where your controls should

    /// be added.  Dynamic controls need to be re-created on each post-back.

    /// </summary>

    /// <param name="e"></param>

    protected override void OnInit(EventArgs e) {
        base.OnInit(e);

        // My button that will cause the form to post back

        myButton = new Button();
        myButton.Text = "Click Me";
        myButton.Click += new EventHandler(myButton_Click);

        // The drop-down list that will be saved by ViewState

        myDropDown = new DropDownList();
        myDropDown.ID = "drpTest";
        myDropDown.Attributes.Add("runat", "server");
        myDropDown.EnableViewState = true;
        myDropDown.Items.Add(new ListItem("Item 1", "1"));
        myDropDown.Items.Add(new ListItem("Item 2", "2"));
        myDropDown.Items.Add(new ListItem("Item 3", "3"));

        // The table that will be used to organize the look of the controls

        myTable = new Table();

        // Adding the drop-down control to the table

        myRow = new TableRow();
        myCell = new TableCell();
        myCell.HorizontalAlign = HorizontalAlign.Left;
        myCell.Controls.Add(myDropDown);
        myRow.Cells.Add(myCell);
        myTable.Rows.Add(myRow);

        // Adding the button control to the table

        myRow = new TableRow();
        myCell = new TableCell();
        myCell.HorizontalAlign = HorizontalAlign.Left;
        myCell.Controls.Add(myButton);
        myRow.Cells.Add(myCell);
        myTable.Rows.Add(myRow);

        // Make sure the table control gets added to the page's form

        foreach (object item in Page.Controls) {
            if (item.GetType() == typeof(HtmlForm)) {
                ((HtmlForm)item).Controls.Add(myTable);
                break;
            }
        }
    }

This code shows how to retrieve the value of the dynamically create drop-down control upon post-back. You cannot just use the request object to get the selected value from the control.

    /// <summary>
    /// This method will show the way to retrieve the data selected in the
    /// drop-down list.
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void myButton_Click(object sender, EventArgs e) {
        Response.Write("Drop-Down List Value: " + ((DropDownList)FindControl("drpTest")).SelectedValue);
    }

Points of Interest

I tried to use this code to create a web control instead of a web page but ran into some problems since setting properties doesn't happen until after the control's load event.  If anyone has an example of how to set property values before the init event I would be interested to see it. 

History

Project Created - 08/30/2006