Jump to content
Xtreme .Net Talk

Recommended Posts

  • Moderators
Posted

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?

 

   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

Visit...Bassic Software
  • *Gurus*
Posted

Why? You don't actually need to set control names.

 

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?

MVP, Visual Developer - .NET

 

Now you see why evil will always triumph - because good is dumb.

 

My free .NET Windows Forms Controls and Articles

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...