redbull redbull - 1 month ago 16
Vb.net Question

Dynamic buttons in vb.net using for loop

I want to deal with the arrangement of the buttons. for example i have 10 buttons, i want that after 5 buttons the next 5 buttons will go to the nextline.
Here is the code that i have used:

For i = 1 To 10

Dim btn As New Button

btn.Width = 40
btn.Height = 30
btn.TextAlign = ContentAlignment.MiddleCenter
If i.ToString.Length = 1 Then
btn.Text = "B" & "0" & i
Else
btn.Text = "B" & i
End If
btn.Visible = True
btn.Tag = "Button" & i
Panel1.Controls.Add(btn)
If i <= 5 Then
btn.Location = New Point(10 * 1 + ((i - 1) * btn.Width), 10)
Else
btn.Location = New Point(10 * 1 + ((i - 1) * btn.Width), 10 * 1 + ((i - 1) * btn.Height))
End If


i get the wrong positioning of the buttons. kindly help me on this.
i always get this kind of position. ex:

* * * * *
*
*
*
*
*


What i want is this:

* * * * *
* * * * *

Answer

Try this:

If i <= 5 Then
    btn.Location = New Point(10 * 1 + ((i - 1) * btn.Width), 10)
Else
    btn.Location = New Point(10 * 1 + ((i - 6) * btn.Width), 10 + btn.Height)
End If

EDIT:

If you wanted to change the loop so that you wanted to multiple lines of buttons then look at this:

Dim noOfButtonsPerLine As Integer = 5
Dim buttonIndex As Integer = 0
Dim y As Integer = 10

For i = 1 To 15

    Dim btn As New Button With {.Height = 40, .Width = 30}

    If buttonIndex = noOfButtonsPerLine Then
        buttonIndex = 1
        y += btn.Height
    Else
        buttonIndex += 1
    End If

    btn.TextAlign = ContentAlignment.MiddleCenter
    If i.ToString.Length = 1 Then
        btn.Text = "B" & "0" & i
    Else
        btn.Text = "B" & i
    End If
    btn.Visible = True
    btn.Tag = "Button" & i
    Panel1.Controls.Add(btn)

    btn.Location = New Point(10 * 1 + ((buttonIndex - 1) * btn.Width), y)

Next

Change the variable noofButtonsPerLine to what suits you. I've gone for 5 as per the question but you can change it and it should adapt.