Reputation: 174
i have a program in Visual Basic 6, and i need create a button in my program with code.
I write this code:
private sub Pulso_click()
dim boton as CommandButton
set boton = new CommandButton
boton.width = 100
boton.height = 30
boton.caption = "MiBoton"
End Sub
but don't run. i have "El uso de la palabra clave New no es valido", in english "keyword New use invalid".
This run in Visual Basic 6
Where is the problem??? Thanks
Upvotes: 1
Views: 4380
Reputation:
This code works for me
Option Explicit
'
Dim WithEvents Cmd1 As CommandButton
'
Private Sub Form_Load()
Set Cmd1 = Controls.Add("vb.commandbutton", "Cmd1")
Cmd1.Width = 2000
Cmd1.Top = Me.Height / 2 - Cmd1.Height / 2 - 100
Cmd1.Left = Me.Width / 2 - Cmd1.Width / 2 - 100
Cmd1.Caption = "Dynamic Button"
Cmd1.Visible = True
End Sub
'
Private Sub Cmd1_click()
MsgBox "I have been Created Dynamically at Run-time", _
, "Dynamic Controls"
End Sub
'
Works with no problems for me, I hope this code works for you, You can also use indexes create one command button and set the index to zero then on form load or whenever you want it to show
Load Command1(1)
Command1(1).Caption = "command2"
Command1(1).Left = Command1(0).Left + Command1(0).Width
Command1(1).Top = Command1(0).Top
Command1(1).Visible = True
You get the point, good luck, I use indexes myself lots of times when I have a bunch of controls it loads faster this way, enjoy.
Upvotes: 3
Reputation:
Your code does not look like it stems from the VB6 IDE. I suppose you have an IDE, right? If so:
You can't create a CommandButton by code just so. If you want one at runtime, you need a control field. To make a control field, place a CommandButton control on your form. Give it the Index 0. Set its Visible property to False.
Your code seems to imply pixels. Set the form's ScaleMode property to 3 - Pixels.
Now you can create further instances from this template.
Private Sub Form_Load()
Load Command1(1)
With Command1(1)
.Top = 10
.Left = 10
.Width = 100
.Height = 30
.Caption = "MiBoton 1"
.Visible = True
.ZOrder
End With
Load Command1(2)
With Command1(2)
.Top = 10
.Left = 120
.Width = 100
.Height = 30
.Caption = "MiBoton 2"
.Visible = True
.ZOrder
End With
End Sub
Upvotes: 1