Add buttons to form at runtime? working on this all day.

R

Ron

Can anyone help me out? I am trying to add buttons numbered one
through 10 at runtime to a form.

I think they are getting added but they seem to be getting stacked one
on top of each other. so I only see 1, and not the others.

here is what I am doing can anyone tell me what I am doing wrong?

Public Class Form1
Public buttons(9) As Button
Const buttonwh As Integer = 30

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

For i = 0 To 9
j = i + 1
pntcurrent = New Point(j + (buttonwh + 8), row)
Call createbuttons(i, pntcurrent)
Next
For k As Integer = 0 To buttons.GetUpperBound(0)
AddHandler buttons(k).Click, AddressOf Button_click
Next
End Sub

Private Sub createbuttons(ByVal i As Integer, _
ByVal pnt As Point)
buttons(i) = New Button
buttons(i).Enabled = True
buttons(i).Visible = True
buttons(i).Text = Convert.ToString(i + 1)
buttons(i).Size = New _
System.Drawing.Size(buttonwh, buttonwh)
buttons(i).Location = pnt
Me.Controls.Add(buttons(i))
End Sub

Private Sub button_click(ByVal sender As System.Object, _
ByVal e As System.EventArgs)

End Sub
End Class
 
M

Mudhead

What is row suppose to be? It's always 0. How about something like this:

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
Dim i, row As Integer
Dim pntcurrent As Point
row = 30
For i = 0 To 9
pntcurrent = New Point((buttonwh + 8), row * i)
Call createbuttons(i, pntcurrent)
Next
For k As Integer = 0 To buttons.GetUpperBound(0)
AddHandler buttons(k).Click, AddressOf button_click
Next
End Sub
 
R

Ron

Ah yes that did it. thank you!

Now what if I wanted to be able to tell what button was being pressed
and know the value of it? Say I want to add a label called
labelbuttons and I want its text property to show 2 if I press
button 2, 3 if i press button three etc?

How would I do this? I just want to make sure that the correct button
referance is there for each button?
 
M

Mudhead

This sounds like a school project. No?

Private Sub button_click(ByVal sender As System.Object, ByVal e As
System.EventArgs)
Label1.Text = DirectCast(sender, Button).Text
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top