Atlanta Custom Software Development 

   Search        Code/Page

User Login



Forgot the Password?
» Web Development
» Maintenance
» Data Integration/BI
» Information Management
» Regular Expr Tester
» Free Tools

Dynamically Add Controls to a Form with Visual Basic 6.0

Total Hit ( 14701)

Rate this article:     Poor     Excellent 

 Submit Your Question/Comment about this article



Visual Basic 6.0 allows you to dynamically add control to a form at run- time using the new Add method of the Controls collection. This article shows how to dynamically add intrinsic and ActiveX controls.
Control     ProgID
CheckBox    VB.CheckBox
ComboBox    VB.ComboBox
CommandButton  VB.CommandButton
Frame      VB.Frame
HScrollBar   VB.HScrollbar
Image      VB.Image
Label      VB.Label
Line      VB.Line
ListBox     VB.ListBox
OptionButton  VB.OptionButton
PictureBox   VB.PictureBox
Shape      VB.Shape
TextBox     VB.TextBox
Timer      VB.Timer
VScrollBar   VB.VScrollBar

In fact, however, you can add any ActiveX control to your form dynamically, as long as you have the correct ProgID. As I mentioned, ProgIDs are defined in the registry and take the general form LibraryName.Control_Name

If you don't know quite where to search in HKEY_CLASSES_ROOT, you can use the Object Browser to get the correct ProgID. Just add the control to your project, open Object Browser, and select the control name in the classes list box. The Object Browser's status pane will then display the control name and the library name. For instance, Figure 1 shows that the ProgID for the TreeView control is MSComctlLib.Treeview

The following example dynamically adds two intrinsic and one ActiveX control to an application at run-time. The sample shows how to program the events of a dynamically added control. If you are dynamically adding a control that is not referenced in the project, you may need to add the control's License key to the Licenses collection. For more information on the Licenses collection, please see the REFERENCES section of this article.

Step-By-Step Example

- Create a new Standard EXE project. Form1 is created by default.
- Add the following code to the code window of Form1:

Click here to copy the following block
Option Explicit
' If you are adding an ActiveX control at run-time that is
' not referenced in your project, you need to declare it
' as VBControlExtender.
Dim WithEvents ctlDynamic As VBControlExtender
Dim WithEvents ctlText As VB.TextBox
Dim WithEvents ctlCommand As VB.CommandButton

Private Sub ctlCommand_Click()
  ctlText.Text = "You Clicked the Command button"
End Sub

Private Sub ctlDynamic_ObjectEvent(Info As EventInfo)
  ' test for the click event of the TreeView
  If Info.Name = "Click" Then
   ctlText.Text = "You clicked " & ctlDynamic.object.selecteditem.Text
  End If
End Sub

Private Sub Form_Load()
  Dim i As Integer
  ' Add the license for the treeview to the license collection.
  ' If the license is already in the collection you will get
  ' the run-time error number 732.
  Licenses.Add "MSComctlLib.TreeCtrl"

  ' Dynamically add a TreeView control to the form.
  ' If you want the control to be added to a different
  ' container such as a Frame or PictureBox, you use the third
  ' parameter of the Controls.Add to specify the container.
  Set ctlDynamic = Controls.Add("MSComctlLib.TreeCtrl", _
          "myctl", Form1)
  ' set the location and size of the control.
  ctlDynamic.Move 1, 1, 2500, 3500

  ' Add some nodes to the control.
  For i = 1 To 10
   ctlDynamic.object.nodes.Add Key:="Test" & Str(i), Text:="Test" _
                    & Str(i)
   ctlDynamic.object.nodes.Add Relative:="Test" & Str(i), _
              Relationship:=4, Text:="TestChild" & Str(i)
  Next i
  ' Make the control visible.
  ctlDynamic.Visible = True

  ' add a textbox
  Set ctlText = Controls.Add("VB.TextBox", "ctlText1", Form1)
  ' Set the location and size of the textbox
  ctlText.Move (ctlDynamic.Left + ctlDynamic.Width + 50), _
         1, 2500, 100

  ' Change the backcolor.
  ctlText.BackColor = vbYellow

  ' Make it visible
  ctlText.Visible = True

  ' Add a CommandButton.
  Set ctlCommand = Controls.Add("VB.CommandButton", _
          "ctlCommand1", Form1)

  ' Set the location and size of the CommandButton.
  ctlCommand.Move (ctlDynamic.Left + ctlDynamic.Width + 50), _
          ctlText.Height + 50, 1500, 500

  ' Set the caption
  ctlCommand.Caption = "Click Me"

  ' Make it visible
  ctlCommand.Visible = True
End Sub

- Save and run the project. Try clicking the CommandButton and on different Nodes in the TreeView. The TextBox will show what you click.

More information

Now we will walk through VBControlExtender Object, ObjectEvent Event, EventParameter Object Examples which are important to know when you deal with dynamic controls.

VBControlExtender Object : Represents the Visual Basic VBControlExtender properties.

The VBControlExtender object is primarily used when dynamically adding a control to the Controls collection using the Add method. The VBControlExtender object is particularly useful for this purpose because it provides a generic set of properties, events, and methods to the developer. Another feature of the object is the ObjectEvent event which is designed to parse any event raised by a dynamically added control. The example below declares an object variable as VBControlExtender, and sets the variable when adding a control. The example also shows how you can program the ObjectEvent event.

Restrictions on Setting the References to the Variable
There is one caveat to be aware of when setting the VBControlExtender object to a dynamically added control: intrinsic controls cannot be set to the variable.

Here is the example

Click here to copy the following block
Option Explicit
Dim WithEvents objExt As VBControlExtender ' Declare VBControlExtender variable WithEvents

Private Sub LoadControl()
  Licenses.Add "Project1.Control1", "ewrinvcmcoe"
  Set objExt = Controls.Add("Project1.Control1", "myCtl")
  objExt.Visible = True ' The control is invisible by default.
End Sub

Private Sub extObj_ObjectEvent(Info As EventInfo)
  ' Program the events of the control using Select Case.
  Select Case Info.Name
  Case "Click"
   ' Handle Click event here.
  ' Other cases now shown
  Case Else ' Unknown Event
   ' Handle unknown events here.
  End Select
End Sub

ObjectEvent Event : Represents event information raised by a control assigned to a VBControlExtender object variable.

The EventInfo object is available in the ObjectEvent event, which is an event of the VBControlExtender object. In common practice, a control that is dynamically added to the Controls collection using the Add method will be assigned to an object variable of the type VBControlExtender. The ObjectEvent event can then be used to trap all events raised by the control, and the EventInfo object specifically represents any parameters passed by the raised events.

The EventInfo object has two properties: the Name property returns the name of the raised event; the EventParameters property returns a reference to the EventParameters collection that allows you to return values of all event parameters.

ObjectEvent Event : Occurs when a control that is assigned to a VBControlExtender object variable raises an event.

Syntax : Private Sub object_ObjectEvent(Info As EventInfo)

The ObjectEvent event syntax has these parts:

Part Description

object Required. An object expression that evaluates to an object in the Applies To list.
Info Returns a reference to an EventInfo object.


The ObjectEvent event is a generic event that allows you to handle events of a control and return values through the control's event parameters.

You can use the ObjectEvent event to trap generic events a control raises, assuring that any control you deploy contains certain basic functionality required by the deployed application.

Here is the ObjectEvent Event, EventParameter Object Examples

The first example below uses the ObjectEvent event to print all parameter names and values.

Click here to copy the following block
Option Explicit
Private WithEvents extObj As VBControlExtender

' Code to set the object variable to a user control not shown.

Private Sub extObj_ObjectEvent(Info As EventInfo)
  Dim p As EventParameter
  Debug.Print Info.Name

  For Each p In Info.EventParameters
   Debug.Print p.Name, p.Value
End Sub

The second example allows you to check for a generic event raised by the control.

Click here to copy the following block
Private Sub extObj_ObjectEvent(Info As EventInfo)
  Dim p As EventParameter
  Select Case Info.Name
  Case "UserName"
   ' Check User name value.
   MsgBox Info.EventParameters("UserName").Value
  ' Other cases now shown
  Case Else ' Unknown Event
   ' Handle unknown events here.
  End Select
End Sub

Submitted By : Nayan Patel  (Member Since : 5/26/2004 12:23:06 PM)

Job Description : He is the moderator of this site and currently working as an independent consultant. He works with, SQL Server and other MS technologies. He is, MCDBA and MCSE. In his free time he likes to watch funny movies and doing oil painting.
View all (893) submissions by this author  (Birth Date : 7/14/1981 )

Home   |  Comment   |  Contact Us   |  Privacy Policy   |  Terms & Conditions   |  BlogsZappySys

© 2008 BinaryWorld LLC. All rights reserved.