Moderators Robby Posted December 19, 2002 Moderators Posted December 19, 2002 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 Quote Visit...Bassic Software
*Gurus* divil Posted December 19, 2002 *Gurus* Posted December 19, 2002 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. Quote MVP, Visual Developer - .NET Now you see why evil will always triumph - because good is dumb. My free .NET Windows Forms Controls and Articles
Moderators Robby Posted December 19, 2002 Author Moderators Posted December 19, 2002 but it would still be btn1, btn2 etc... I was thinking something like... btn & i i being an integer Quote Visit...Bassic Software
*Gurus* divil Posted December 19, 2002 *Gurus* Posted December 19, 2002 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? Quote MVP, Visual Developer - .NET Now you see why evil will always triumph - because good is dumb. My free .NET Windows Forms Controls and Articles
Moderators Robby Posted December 19, 2002 Author Moderators Posted December 19, 2002 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. Quote Visit...Bassic Software
*Gurus* divil Posted December 19, 2002 *Gurus* Posted December 19, 2002 :) Quote MVP, Visual Developer - .NET Now you see why evil will always triumph - because good is dumb. My free .NET Windows Forms Controls and Articles
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.