C# Programming > Windows Forms

C# Dynamic Controls

Dynamic Control

A dynamic control in C# is a control that is created at run-time as opposed to design-time. The advantages of C# dynamic controls is that they can be created in response to how the user interacts with the application...

Common controls that are added during run-time are the Button and TextBox controls. But of course, nearly every C# control can be created dynamically.

Challenges of Dynamic Controls

Part of the challenge in creating C# controls at run-time is that there is nothing automatic from design-time. Properties like Size and Location have to be set manually by the programmer.

Another tricky part is manually attaching Events to dynamic controls. The C# code for the events must be pre-written and must be written in a way that each dynamic control will behave appropriately. For example, the same Click event might be attached to several different Button controls, but it most know how to behave depending on which button called it.

Working with Dynamic Controls

As far as Size and Location goes, it helps to first design the interface visually at design-time as a reference. For more advanced user interface aligning, there are simple functions to help you.

For events, a simple strategy is to stick to a naming structure. For example, name dynamic buttons with "myButton1", "myButton2", etc. That way the called event can use the name to infer which dynamic control was accessed.

C# Example

At the bottom of the page you can download an example of working with dynamic controls in C#. The sample application creates some textboxes and buttons that each behave with a single Event...

Back to C# Article List