Dynamically adding and removing controls at runtime

You may find situations where you can't create user interface controls ahead of time. Fortunately you can add and remove controls in desktop, mobile and web apps dynamically at runtime.

Note

If you are creating additional controls and need them to share the same event handlers, consider using a Control Set.

Creating and destroying a control instance

A control is simply an instance of a class. With that in mind, you create one the same way you create any instance of a class, with the New method. Accordingly, as with any class instance, you need to store the instance in some container (a variable, a property, etc.) that can keep it for as long as you need it.

If you only need the control itself, you can create an instance of that control directly. In this example, an instance of a DesktopTextField is created and stored in a property of the window upon which it's going to be placed:

UserName = New DesktopTextField

If you need the control to respond to events, add a subclass of the control to your project and then create an instance of your subclass. In this example, UserNameField is a class that has been added to the project. It's Super property has been set to DesktopTextField:

UserName = New UserNameField

Unlike dragging a control from the Library to a layout, when you create a control instance, none of the properties have default values. This means you need to set all of them including their Left, Top, Width, Height and more. In this example, a DesktopTextField is created and default values set for some properties:

UserName = New DesktopTextField
UserName.Left = 100
UserName.Top = 100
UserName.Width = 200
UserName.Height = 22
UserName.Hint = "Enter a username here"

When you no longer need the control instance, you can destroy it by calling the control's Close method:

UserName.Close

Of course since closing the instance destroys it, it also removes it from the layout.

Adding controls to a layout

Create a control instance does not add it to the layout. To do that, call the AddControl method of the layout (DesktopWindow, MobileScreen or WebPage). In this example, the control instance is being added in the Opening event of the layout:

UserName = New DesktopTextField
UserName.Left = 100
UserName.Top = 100
UserName.Width = 200
UserName.Height = 22
UserName.Hint = "Enter a username here"
AddControl(UserName)

Removing controls from a layout

To remove a control, use its Close method. In this example, the control is being removed from the Pressed event of a button:

UserName.Close

See also

AddControl method for DesktopWindow, MobileScreen and WebPage; Close method for DesktopControl, MobileScreen and WebControl