Add Controls to a Web Form Dynamically

Problem

You want to add a Web control to a Web page at run time and handle its events.

Solution

Create a control object, add it to the Controls collection of a container control, and use the AddHandler statement to connect any event handlers. You must create the control after every postback.

Discussion

You can use a similar technique to add Web controls to a Web page as you would use to add Windows controls to a form, but there are some differences, including:

  • Dynamically added controls will exist only until the next postback. If you need them, you must re-create them when the page is returned. This requirement does not prevent you from handling their events, however.

  • Dynamically added controls are not as easy to ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.