Question Dynamic Buttons

jhaynes

New member
Joined
Jun 6, 2011
Messages
4
Programming Experience
1-3
Hello All,
I am new to the group, and this seems like an appropriate place for my question.
I am creating a windows console app, with .net 3.5. I would like to be able to dynamically display buttons based on user need. As this is for dynamic research the number of buttons need to change...not often, but to minimize code complexity it would be nice. Today it is 5, tomorrow it could be 15. Here is the sudo code of what I would like:

int NumberofButtons = 5
for (i = 0 to NumberofButtons)
- add new button
- Set name and text of button. (I know how to do this)
- position button

Thank you for your help,
Justin
 

Attachments

  • TreeDiagram.bmp
    263.7 KB · Views: 36
Here's an example:

Dim oldX As Integer = 10
Dim oldY As Integer = 10

Private Sub AddButtons()
    Dim NumberOfButtons As Integer = 5
    Dim Name() As String = {"Button1", "Button2", "Button3", "Button4", "Button5", "Button6"}
    Dim Text() As String = {"Button1", "Button2", "Button3", "Button4", "Button5", "Button6"}
    For i = 0 To NumberOfButtons
        Dim NewButton As New Button 'Create a new button
        NewButton.Text = Name(i) 'Set the NewButton's Name property based on the Name array above
        NewButton.Name = Text(i) 'Set the NewButton's Text property based on the Text array above
        NewButton.Location = getLocation(NewButton) 'Set the location, see the function "getLocation" below
        Me.Controls.Add(NewButton) 'Add the NewButton to the form
        AddHandler NewButton.Click, AddressOf buttonClick 'This will make it so you can have a Click event
    Next
End Sub

Private Function getLocation(ByVal NewButton As Button) As Point 'This will return the "next point" so to speak, it basically adds the buttons width + 10 each time, if it runs out of room it will move down on Y
    Dim pReturn As Point = New Point(oldX, oldY)
    oldX += 10 + NewButton.Width
    If (oldX + NewButton.Width) > (Me.Width - 10) Then oldY += 10 + NewButton.Height : oldX = 10
    Return pReturn
End Function

Private Sub buttonClick(ByVal sender As Object, ByVal e As EventArgs)
    Dim b As Button = sender 'Get's you the button that was clicked
    'Do your button click here
End Sub

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    AddButtons()
End Sub


Hope this helps
-Josh
 
Hi Josh,
Thank you for your help, it worked well. The only problem is that I am getting duplicate buttons.

Button1 Button 2 Button 3
Button1 Button 2 Button 3

Do you know how to fix this?
 
Duplicates? That's odd, it works fine for me. Did you modify the code at all?
 
:) Glad it worked.
 
Using one of the container controls FlowLayoutPanel or TableLayoutPanel would simplify placement of controls added.
 
Back
Top