Dynamically Create Controls

  • Thread starter Thread starter torey
  • Start date Start date
T

torey

Guest
I am trying to dynamically create a control (CheckBox) during runtime and place it on the form. Any Ideas?
 
Private WithEvents chk As CheckBox

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
chk = New CheckBox()
chk.Text = "hehe"
chk.Top = 0
chk.Left = 0
Me.Controls.Add(chk)
AddHandler chk.CheckStateChanged, AddressOf chk_CheckedChanged
End Sub

Private Sub chk_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
MsgBox("checkbox's state changed to " & sender.Checked)
End Sub
 
if you want to create multiple controls by looping do like this

if you want to create multiple controls by looping do like this
Dim chk() As CheckBox

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim i As Integer

For i = 0 To 5
ReDim Preserve chk(i)
chk(i) = New CheckBox()
chk(i).Text = "check " & i
chk(i).Top = chk(i).Height * i
chk(i).Left = 0
chk(i).Name = "chk" & i
Me.Controls.Add(chk(i))
AddHandler chk(i).CheckStateChanged, AddressOf chk_CheckedChanged
Next
End Sub

Private Sub chk_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
MsgBox("checkbox " & sender.name & "'s state changed to " & sender.Checked)
End Sub
 
Back
Top