vb.net中的动态按钮使用for循环

时间:2016-10-27 08:25:46

标签: vb.net

我想处理按钮的排列。例如,我有10个按钮,我希望在5个按钮后,接下来的5个按钮将转到下一行。 这是我使用过的代码:

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

我得到了错误的按钮定位。请帮助我。 我总是得到这种立场。例如:

* * * * *
         *
          *
           *
            *
             *

我想要的是:

* * * * *
* * * * *

附加:我如何使用backgroundworker来做...?

2 个答案:

答案 0 :(得分:2)

假设您使用的是winforms,而不是尝试手动定位按钮,我建议您使用FlowLayoutPanel控件而不是直接面板。然后你可以添加它们,让面板管理它们的位置。

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

    FlowLayoutPanel1.Controls.Add(btn)
Next

如果每行必须有5个(假设您的面板足够宽),可以使用SetFlowBreak

For i = 1 to 10

    '.....

    FlowLayoutPanel1.Controls.Add(btn)

    'Use this line if you must have only 5 buttons per line.
    if i Mod 5 = 0 Then FlowLayoutPanel1.SetFlowBreak(btn, true)
Next

答案 1 :(得分:1)

试试这个:

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

修改

如果您想更改循环以便想要多行按钮,请查看以下内容:

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

将变量noofButtonsPerLine更改为适合您的变量。我按照问题去了 5 ,但你可以改变它,它应该适应。