9.1. Add a Control Programmatically

Problem

You need to add a control to a form at runtime, not design time.

Solution

Create an instance of the appropriate control class. Then add the control object to a form or a container control by calling Controls.Add on the container. (The container's Controls property returns a ControlCollection instance.)

How It Works

In a .NET form-based application, there is really no difference between creating a control at design time and creating it at runtime. When you create controls at design time (using a tool such as Microsoft Visual Studio), the necessary code is added to your form class. Visual Studio places this code in a separate source file using the partial type functionality. You can use the same code ...

Get Visual Basic 2008 Recipes: A Problem-Solution Approach 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.