Elias
Elias

Reputation: 39

How use New keyword to create a New object in VB6, such as new button, label, etc

I have a program that get several names, and save them in a file. I want to create a new object (button, label, etc) for every person that saved in the file. I use this code, but I got error :

Dim i as new object
set i= new button

The error that I got : ActiveX Component can't create object

Upvotes: 3

Views: 381

Answers (1)

deblocker
deblocker

Reputation: 7697

In your Form, add a Label and a Command Button. I assume you already did this.

Select the label and, inside the Properties Window, set lblPerson to the Name property and 0 to the Index property.

Select the button and, inside the Properties Window, set cmdPerson to the Name property and 0 to the Index property.

Now you have two Control Arrays which you can dynamically set at runtime:

Public Sub AddPersonListControls(idx As Long)
    Load cmdPerson(idx)
    cmdPerson(idx).Caption = "Details"
    cmdPerson(idx).Visible = True
    cmdPerson(idx).Top = cmdPerson(idx - 1).Top + cmdPerson(idx - 1).Height + 10
    cmdPerson(idx).Left = cmdPerson(0).Left

    Load lblPerson(idx)
    lblPerson(idx).Caption = "Person Name " & idx
    lblPerson(idx).Visible = True
    lblPerson(idx).Top = lblPerson(idx - 1).Top + lblPerson(idx - 1).Height + 10
    lblPerson(idx).Left = lblPerson(0).Left
End Sub

Wherever you load the data of your Persons, create the corresponding controls:

Dim numPersons As Long 
numPersons = 3 ' just an example
Dim i As Long
For i = 1 To numPersons - 1
    AddPersonListControls i
Next

Your form should looks like this (Note: Form1.ScaleMode is set to 3-Pixels):

Dynamically loaded controls

Explanation:

While my answer doesn't directly address your question with the New keyword, it shows you the right method how to dynamically add new Controls in the case you don't know how much they should be, thus by avoiding the use of Named Controls and by using instead Array Controls.

Upvotes: 2

Related Questions