Sunday, June 10, 2007

Programmatically Add Controls At Runtime

As I have experienced it, in some situations, you might not know the types of control or how many controls will be needed at design time. In these cases, you'd have to create the controls programmatically and dynamically add them to the form at runtime.

Adding controls at runtime is pretty simple:

Dim newControl as New Windows.Forms.CheckBox
newControl.Name = "chkCheckAll"
newControl.Text = "check all"
newControl.Top = 10
newControl.Left = 10me.Controls.Add(newControl)

The code snippet above will declare a checkbox and add it to the current form.

If you don't know the type of control then it'd be best to declare the new control as a generic control and then later modify to suite your need.

Dim newControl as Windows.Forms.Control
If createCheckBox Then
newControl = New Windows.Forms.CheckBox
Else
newControl = New Windows.Forms.RadioButton
End If

I find the .Tag property particularly helpful when working with controls dynamically. You can use it to store specific information about the control and you it later on when you process the control.

This blog only touches some of the properties for CheckBox & RadioButton as I try to keep the blog short. You should further explore their other properties to gain more understanding about them.

Now that you know how to add controls at runtime, let's see how you can programmatically remove them.

2 comments:

Anonymous said...

Amiable brief and this post helped me alot in my college assignement. Thanks you seeking your information.

Anonymous said...

Sorry for my bad english. Thank you so much for your good post. Your post helped me in my college assignment, If you can provide me more details please email me.