Controls at Runtime

Robby

Ultimate Contributor
Joined
Nov 17, 2002
Messages
3,460
Location
Montreal, Ca.
I'm bored and fooling around, anyway....

There have been a few questions today about creating controls at runtime, hence the fooling around. (Did I mention I was bored)
The following code creates 3 buttons, but is still hard-coded, there must be a way of making this more dynamic.
Any ideas?

Visual Basic:
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim btn1 As New Button()
        Dim btn2 As New Button()
        Dim btn3 As New Button()

        With btn1
            AddHandler .Click, AddressOf btnClick
            .Text = "button 1"
            .Location = New Point(0, 50)
            .Size = New Size(100, 50)
        End With
        With btn2
            AddHandler .Click, AddressOf btnClick
            .Text = "button 2"
            .Location = New Point(0, 150)
            .Size = New Size(100, 50)
        End With
        With btn3
            AddHandler .Click, AddressOf btnClick
            .Text = "button 3"
            .Location = New Point(0, 250)
            .Size = New Size(100, 50)
        End With

        Controls.Add(btn1)
        Controls.Add(btn2)
        Controls.Add(btn3)
    End Sub

    Private Sub btnClick(ByVal sender As Object, ByVal e As EventArgs)
        MessageBox.Show("You clicked ... " & DirectCast(DirectCast(sender, Button).Text, String))
    End Sub
 
I guess you could use a For loop to instantiate them and place them on the form at appropriate places. You could add them to the controls collection in the loop.
 
Why? You don't actually need to set control names.

Visual Basic:
For i = 1 To 10
  btn = New Button()
  With btn
    AddHandler .Click, AddressOf btnClick
    .Text = "button 2"
    .Location = New Point(0, i * 30)
    .Size = New Size(100, 50)
  End With
  Controls.Add(btn)
Next

Why not do something like that?
 
funny thing, before posting this thread, I did exactly the same thing, except that I had placed

Dim btn As New Button()

inside the loop.

thanks divil.
 
Back
Top