Working with Controls Dynamically in Code

Each control in the Toolbox is a member of the Control class in the System.Windows.Forms namespace. Because each control in the Toolbox is a class, similar to a Window Forms class, you can dynamically create controls in code at runtime. Earlier you looked at the InitializeComponent method, which created the controls on the form. You can do the same type of dynamic code creation when writing applications. Doing so gives you flexibility in the user interface and enables you to create complete forms based on user settings that might be stored in a database or configuration file.

To find out how to create controls dynamically at runtime, add the code in Listing 3.4 to the Form_Load event of firstForm.

Listing ...

Get Sams Teach Yourself Visual Studio® .NET 2003 in 21 Days 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.