Export (0) Print
Expand All

Adding Controls to a Web Forms Page Programmatically

There are times when it is more practical to create a control at run time than at design time. For example, imagine a search results page in which you want to display results in a table. Because you do not know how many items will be returned, you want to dynamically generate one table row for each returned item.

Note   Existing controls can often provide the functionality you get from creating controls dynamically. For example, controls such as the Repeater, DataList, and RadioButtonList controls can dynamically create rows or other control elements when the page runs.

In order to programmatically add a control to a page, there must be a container for the new control. For example, if you are creating table rows, the container is the table. If there is no obvious control to act as container, you can use a Placeholder or Panel Web server control.

In some instances, you might want to create both static text and controls. To create static text, you can use either a Literal or a Label Web server control. You can then add these controls to the container as you would any other control.

Note   Manipulating controls programmatically is often used when creating composite controls. For details, see Developing a Composite Control.

Dynamic Controls and View State

When a control is created dynamically at run time, some information about the control is stored in the view state that is rendered with the page. When the page is posted back to the server, however, non-dynamic controls (those defined on the page) are instantiated in the Page.Init event and view state information is loaded before the dynamic controls can be recreated (generally in the Page_Load handler). Effectively, before the dynamic controls are recreated, view state is temporarily out of sync with the page's controls. After the Page_Load event has run, but before control event handling methods are called, the remaining view state information is loaded into the dynamically created controls.

In most scenarios, this view state processing model works fine. Typically, you add dynamic controls to the end of a container's collection of controls. The view state information stored for the dynamic controls is therefore extra information at the end of the view state structure for the appropriate container, and the page can ignore it until after the controls are created.

However, view state information about dynamically created controls can be a problem in two scenarios:

  • If you insert dynamic controls between existing controls.
  • If you insert controls dynamically and then reinsert them during a round trip, but with different values.

If you insert dynamic controls between existing controls, the dynamic control's view state information is inserted into the corresponding location of the view state structure. When the page is posted and the view state is loaded, the dynamic control does not yet exist; therefore, the extra information in view state does not correspond to the right control. The result is usually an error indicating an invalid cast.

If you reinsert controls with each round trip, each generation of dynamically created controls will pick up property values from the view state of the preceding set of controls. In many cases, you can avoid this problem by setting the EnableViewState property of the container control to false. In that case, no information about the dynamic controls is saved, and there is no conflict with successive versions of the controls.

For details about view state, see Web Forms Page Processing, Introduction to Web Forms State Management, and Control.ViewState.

To add a control to a Web Forms page programmatically

  1. Create an instance of the control and set its properties:
    ' Visual Basic
    Dim myLabel As Label = New Label()
    myLabel.Text = "Sample Label"
    
    // C#
    Label myLabel = new Label();
    myLabel.Text = "Sample Label";
    
    Tip   Controls are typically added to the page during the page's load stage. For details about page stages, see Web Forms Page Processing.
  2. Add the new control to the Controls collection of a container already on the page:
    ' Visual Basic
    Panel1.Controls.Add(myLabel)
    
    // C#
    Panel1.Controls.Add(myLabel);
    
    Note   Because Controls is a collection, it is possible to use the AddAt method to place the new control at a specific location — for example, in front of other controls. However, this can introduce errors into the page. For details, see "Dynamic Controls and View State" earlier in this topic.

    The following example shows the event handler for the SelectedIndexChanged event of a control called "DropDownList1". The handler creates as many label controls as the user has selected from the drop-down list. The labels display the word "Label" plus a counter. The container for the controls is a Placeholder Web server control called "Placeholder1."

    Security Note   User input in a Web Forms page can include potentially malicious client script. By default, the Web Forms page validates that user input does not include script or HTML elements. For more information, see Scripting Exploits and Protecting Against Script Exploits in a Web Application.
    ' Visual Basic
    Private Sub DropDownList1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles DropDownList1.SelectedIndexChanged
       Dim i As Integer
       Dim numlabels As Integer
       ' Get the number of labels to create.
       numlabels = CInt(DropDownList1.SelectedItem.Text)
       For i = 1 To numlabels
          Dim myLabel As Label = New Label()
          ' Set the label's Text and ID properties.
          myLabel.Text = "Label " & i
          myLabel.ID = "Label" & i
          PlaceHolder1.Controls.Add(myLabel)
          ' Add a spacer in the form of an HTML <BR> element
          Dim spacer As LiteralControl = New LiteralControl("<br>")
          PlaceHolder1.Controls.Add(spacer)
       Next
    End Sub
    
    // C#
    private void DropDownList1_SelectedIndexChanged(object sender, System.EventArgs e)
    {
       // Get the number of labels to create.
       int numlabels = System.Convert.ToInt32(DropDownList1.SelectedItem.Text);
       for (int i=1; i<=numlabels; i++)
       {
          Label myLabel = new Label();
          // Set the label's Text and ID properties.
          myLabel.Text = "Label" + i.ToString();
          myLabel.ID = "Label" + i.ToString();
          PlaceHolder1.Controls.Add(myLabel);
          // Add a spacer in the form of an HTML <BR> element.
          PlaceHolder1.Controls.Add(new LiteralControl("<br>"));
       }
    }
    

See Also

Setting Web Server Control Properties Programmatically | Setting HTML Server Control Properties Programmatically | ASP.NET Server Controls | Referencing Controls in Web Forms Pages

Show:
© 2014 Microsoft