# VBForums UtilityBank > UtilityBank - Tutorials >  [VB] How to load a control at runtime.

## NoteMe

Loading objects at runtime is not used much in VB(5/6). In a lot of other programming languages it is the only way to do it. But in VB most users like just to drop the desired object on the form, and costumize them in the IDE.
Some times it can be better to do this at run time. You can save some memory by doing this. Or you can save a lot of work if you want many many objects of the same type at a form, by loading them as a control array. One thing to think about though is that loading a lot of objects at run time can take a lot of time. So you have to carefully think about when to load them and when to show them. But now lets get to work. I am going to show you 3 ways to do this. There is more ways to do it. But I don't think you need more then maximum 3 right now.
The first way I will show you is just loading one single object. You can write event code for them at design time if you want, but the object can't use it before it has been made at run time. In this example I will make the object in the form load event. So when the form appears on the screen it will show right away. You can of course change this to any prefered event.


First you have to make a pointer to the kind of object you want to make. You do this by writing


VB Code:
Dim WithEvents cmdButton As CommandButton



You declear it more or less as a normal variable using Dim. The data type is CommandButton. The WitEvents keyword tells the app that you want to make it possible to write event code for the command button you are writing. But this pointer is not pointing to anything. It can point to a command button, but we have no command button yet. But we will make that soon. But first we will will write an Sub for the commandbutton we have made. Nothing new here. The Sub looks like this:


VB Code:
Private Sub cmdButton_Click() 
     MsgBox "hi"
End Sub



It looks just like a normal Sub you are writing. It is triggered when the click event of the command button is made. And it makes a message box appear with "hi" as the text.
No lets make the command button. As I said earlier I will write it in the forms load event. First we will make the command button like this:


VB Code:
Set cmdButton = Me.Controls.Add("VB.CommandButton", "newCommandButton" )


Now we are setting the pointer that we made earlier to point to a new command button that we are making. We do that my setting it = Me.Controls.Add("VB.CommandButton", "newCommandButton" ). Me is the an "acronym" to the form you are using. If the form you are using is called Form1, you could as well write


VB Code:
Set cmdButton = Form1.Controls.Add("VB.CommandButton", "newCommandButton" )



Controls has a function for making new objects. It takes two parameteters. The first one takes the type of object you want to make. Here it is VB.CommandButton. VB is an object in Visual Basic, and that has a lot of functions and properties. And here we are telling the Add function that we want a command button object. The next parameter is the new name of the object. I have called it newCommandButton, but you can call it what ever you want.
Now we have made the object. But we have not told the app how it looks like. Lets do that now.


VB Code:
With cmdButton 
        .Left = 1000 
        .Top = 1000 
        .Width = 2000 
        .Height = 500
        .Caption = "Hello"
        .Visible = True
End With



Here I am changing all the properties in the With block, but you can of course change all of them one by one if you like that. But the importent thing to notice here is that you have to set the Visible property to true to make it appear on the screen.
Now you have made the object and you are done. At least nearly there. You can do what ever you want with it, but you have a possible memory leak in the app. You don't need the pointer any more. So you should set that one to nothing. You do that like this:


VB Code:
Set cmbButton = Nothing



Now you are finished. But you can't use the pointer to change the properties anymore like we did 2 minutes ago. But you can still change properties by using the new name you made for it. Like this:


VB Code:
Controls("newCommandButton" ).Visible = False



But you can't use the Subs you have made for the command button after you did set the pointer to nothing. So don't do that before you don't need the pointer anymore. So lets wrap this up with the final code you need. And remember you don't need any controls on the form at design time to make this code work.


VB Code:
Option Explicit 
 
Dim WithEvents cmdButton As CommandButton
 Private Sub cmdButton_Click()
     MsgBox "hi"
End Sub
  Private Sub Form_Load() 
     Set cmdButton = Form1.Controls.Add("VB.CommandButton", "newCommandButton" ) 
     
    With cmbButton 
        .Left = 1000 
        .Top = 1000 
        .Width = 2000 
        .Height = 500
        .Caption = "Hello"
        .Visible = True
     End With
 End Sub
 Private Sub Form_Unload(Cancel As Integer)
    Set cmdButton = Nothing
End Sub



Thats all. 

ØØ

----------


## NoteMe

The next example I am going to show you are not that diffrent. So lets go a bit faster thrue this time. I will now make an array of controls of the same type. The problem here is that you can't make event code for the object. The last tehnique after this one will shoe you how you can accomplishe that.
So lets start. First we have to make an array of pointers that can point to the command buttons that we like. You do that nearly the same way you did las time:


VB Code:
Dim cmdButton(4) As CommandButton



The only diffrence is that you this time made an array. (4) shows you that you now have made 5 pointers to the array. From 0 to 4. And the other thing is that we have omitted the WithEvents keyword. That is becuase we can't write event code for a controllaray that we have made at run time yet. But now it is time to make the objects. Lets make a simple loop to go through the pointers and make the objects.


VB Code:
Dim i As Integer
     For i = 0 To 4 
        Set cmdNew(i) = Me.Controls.Add("VB.CommandButton", "cmdButton" & Me.Controls.Count) 
        With cmdNew(i) 
            .Left = 750 * i 
            .Top = 1000 
            .Width = 700
            .Height = 500
            .Caption = "Hello"
            .Visible = True
         End With
    Next i



This example is using a simple for loop so you don't have to write the code 5 times to make the objects. The only thing that is diffrent here is that we have added "& Me.Controls.Count" to the name parameter in the add funtion. We have done that just to make diffrent names of the commandbuttons that we have mede. The other thing that is changed is that I have changed the .Left property to 750 * i just to make sure that the object are not on top of each other, so you can see all of them. After this you just have to set all the pointer to Nothing like we did in the first example when you are finished wiht them. And there is nothing more to it then that. So here is the whole code.


VB Code:
Dim cmdButton(4) As CommandButton 
 
Private Sub Form_Load() 
 
    Dim i As Integer
     For i = 0 To 4 
        Set cmdButton(i) = Me.Controls.Add("VB.CommandButton", "cmdButton" & Me.Controls.Count) 
        With cmdButton(i) 
            .Left = 750 * i 
            .Top = 1000 
            .Width = 700
            .Height = 500
            .Caption = "Hello"
            .Visible = True
        End With
    Next i
 End Sub 
 
Private Sub Form_Unload(Cancel As Integer) 
 
    Dim i As Integer
     For i = 0 To 4
        Set cmdButton(i) = Nothing
    Next i 
     
End Sub




ØØ

----------


## NoteMe

Now for the last example you need to use the IDE a bit more. The simples way to accomplish this is to make a command button or what ever you want and drag it to the form like you normaly do. Change the name to what you want. Like I did: cmdButton. Then copy the command button and paste it to the form again. Then you will have a pop up message that asks you if you want to make a control array. Press yes. Then you have a control array called cmdButton of type command buttons. Now you can delete the second command buttons if you want. Becuase now we are going to load as many as we want using code. You do it like this:


VB Code:
Private Sub Form_Load() 
 
    Dim i As Integer
     For i = 1 To 4
        Load cmdButton(i) 
        With cmdButton(i) 
            .Left = 750 * i 
            .Top = 1000 
            .Width = 700
            .Height = 500
            .Caption = "Hello"
            .Visible = True
        End With
    Next i 
 End Sub



And that is all you need. You don't have to make pointers, and you don't have to set any pointers to nothing. Pretty simple. Just remember that you have all ready loaded at least one object, so you can't load that one again. That is why my for loop goes from 1 and not 0. If I didn't delete the second command button that I made, then it had to go from 2 and so on. We are using the load function to load a new instance. Remember no paranteses around the object that you want to load. The rest of the code you have looked at all ready. This way you can make a lot of things easier. But remember that it takes a lot of CPU power to load the objects. So if you are making a progress bar or anything this way and you are loading the object while you are showing the progress a lot of the CPU power will go to make the objects. So it can be a better to make the objects earlier in the app, and then show them when you need it. But you will probably find out what is best for you when you are making the app. If you have questions about this tutorial please post a question in the forum, where there is probably more then just me that can answer.


ØØ

----------


## MartinLiss

In reference to the 3rd example where you create a control via the IDE, it's not necessary to create a second member (and then possibly delete it) in order to accomplish the creation. Instead all you need to do is to place one control on the form and change its Index to 0 and that will make it a control array.

It should also be noted that while you can Unload any members of the control array that are created at run time you can't Unload the member(s) created in the IDE.

Finally if you want to check the status of the members of a checkbox control array for example and the possibility exists that you might have Unloaded one of the middle members then do this.



```
    Dim cb As CheckBox
    
    For Each cb In Check1 ' The control array
        If cb.Value = vbChecked Then
            MsgBox "My Index is " & cb.Index
        End If
    Next
```

----------


## Tariq Hasan

Dear Friend

Thanks for your help. In your second example where you have used the arrayed control, how do we write events control array? What is the necessity of loading so many command button unless i can define the actions for each button. I have used for second example extensively in one of my form. But stuck up now. Pl advice me how to write events for control array using run time array control method (controls.add method)    . Thanks

----------


## MartinLiss

What I do is to add (for example) a command button and in the IDE set the Index to 0. That will create a control array. When you do that the header for the Click event will look like this and it contains the Index parameter which relates to the Index of the command button.


```
Private Sub Command1_Click(Index As Integer)

Select Case Index
    Case 0
        'do something
    Case 1
        'do something else
    Case 2
        'do something different
End Select
End Sub
```

----------


## Tariq Hasan

Thanks for your early reply. Is there any other option for writing event other than adding a control in IDE. I like to add all the controls during run time and a single event for the control arrays. Thanks in advance

----------


## MartinLiss

Try this little demo. It's the way I do it. After clicking the main button 3 times you can click on the new ones that show up.

----------


## Bonnie West

> Pl advice me how to write events for control array using run time array control method (controls.add method)


See Classic VB - Why can't I use WithEvents on arrays of objects?




> Is there any other option for writing event other than adding a control in IDE. I like to add all the controls during run time and a single event for the control arrays.


See this post.

----------

