5.5. Adding User Controls Dynamically

Problem

You need to load a group of user controls programmatically at runtime because the number of controls required is unknown at design time.

Solution

Bind your data to a Repeater control in the normal fashion and then, as data is bound to each row of the Repeater, use the ItemDataBound event to load a user control dynamically and place it in a table cell of the Repeater control’s ItemTemplate.

Add a Repeater control to the .aspx file with a table cell in the ItemTemplate where the user control is to be placed.

In the code-behind class, use the .NET language of your choice to:

  1. Bind the data to the Repeater control.

  2. Create an event handler method for the ItemDataBound event of the Repeater control.

  3. In the method that handles the ItemDataBound event, use the LoadControl method to create an instance of the user control, and then add the loaded control to the controls collection of the table cell in the ItemTemplate.

Figure 5-5 shows a form where we start with the user controls created in Recipe 5.4 and dynamically load three user controls at runtime. Example 5-26 shows the .aspx file that implements this solution, while Examples 5-27 and 5-28 show the companion VB and C# code-behind files.

Discussion

This recipe demonstrates how to load a group of user controls dynamically into a form, the count for which can be determined only at runtime. A Repeater control is used because it generates a lightweight read-only tabular display and is templatedriven. The ...

Get ASP.NET 2.0 Cookbook, 2nd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.