Private Sub Form_Load()
Dim ctrl1 as control
Set ctrl1 = myfrm.Controls.Add("VB.CommandButton", "Team1", Me)
ctrl1.Visible = True
End Sub
Sub TestClick()
Msg "button clicked!"
End Sub
Printable View
Private Sub Form_Load()
Dim ctrl1 as control
Set ctrl1 = myfrm.Controls.Add("VB.CommandButton", "Team1", Me)
ctrl1.Visible = True
End Sub
Sub TestClick()
Msg "button clicked!"
End Sub
There is WithEvents keyword that needs to be used if you want to event handler(s):
Code:Option Explicit
Dim WithEvents btn As CommandButton
Private Sub Form_Load()
Set btn = Me.Controls.Add("VB.CommandButton", "btnExit")
btn.Move 1000, 1000
btn.Caption = "Exit"
btn.Visible = True
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
Me.Controls.Remove "btnExit"
End Sub
Private Sub btn_Click()
Unload Me
End Sub
Here are two options, there may be a couple more.
1. Don't add VB controls that way, rather use a hidden dummy control, indexed at zero. Then dynamically load the controls using VB's Load method. You will have the built in handlers available to you.
2. Declare the button's object in the declaration section. Edited: RhinoBull beat me to this one.
This FAQ thread may be useful alsoCode:' in declarations section
Dim WithEvents myTestControl As VB.CommandButton
Private Sub Form_Load()
Set myTestControl = myfrm.Controls.Add("VB.CommandButton", "Team1", Me)
myTestControl.Visible = True
End Sub
Private Sub myTestControl_Click()
MsgBox "Got Click"
End Sub
There is yet another method using VB's VBControlExtender object, but that cannot be used with VB's intrinsic controls.
I agree about using control array - it's more flexible and headach less approach.
Thanks for all your answers this is very helpful. Godbless!:wave: