Vb.net 添加到FlowLayoutPanel的按钮相互叠加

Vb.net 添加到FlowLayoutPanel的按钮相互叠加,vb.net,Vb.net,我使用的是VS2012(vb.net),我有一个带有flowLayoutPanel的表单,它包含未知数量的按钮。为了简单起见,基本上,当表单加载时,我会根据一些条件从表中获取项目,然后使用For…Next块为每个项目向flowLayoutPanel添加一个按钮。因此,如果我找到5个项目,我会添加5个按钮,所有这些按钮的名称都不同,但问题是它们似乎相互堆积,而不是整齐排列。当我使用一个按钮一个接一个地添加项目时,它工作正常,但当我使用For…Next块时,它不工作。我尝试在添加每个按钮后刷新flo

我使用的是VS2012(vb.net),我有一个带有flowLayoutPanel的表单,它包含未知数量的按钮。为了简单起见,基本上,当表单加载时,我会根据一些条件从表中获取项目,然后使用For…Next块为每个项目向flowLayoutPanel添加一个按钮。因此,如果我找到5个项目,我会添加5个按钮,所有这些按钮的名称都不同,但问题是它们似乎相互堆积,而不是整齐排列。当我使用一个按钮一个接一个地添加项目时,它工作正常,但当我使用For…Next块时,它不工作。我尝试在添加每个按钮后刷新flowLayoutPanel,我尝试设置每个新按钮相对于上一个按钮位置的位置,但它仍然可以工作。 我已经研究了一个多星期了,有很多东西在那里,但没有专门处理这个

谢谢你的帮助

这是我的代码的相关部分:

`试一试 如果连接状态连接状态打开,则 康涅狄格州公开赛 如果结束

        sql = "SELECT ItemCode, Description, NormalPrice FROM items WHERE items.Class = 'ICE CREAM'"
        cmd = New MySqlCommand(sql, conn)
        da.SelectCommand = cmd
        'fill dataset
        da.Fill(ds, "items")
        rowscount = ds.Tables("items").Rows.Count

        If rowscount > 0 Then 'there are records so go ahead
            Dim ID As Integer
            Dim desc As String
            Dim newbutton As New Button
            Dim newCode As New TextBox

            For i As Integer = 0 To rowscount - 1
                ID = ds.Tables("items").Rows(i).Item("ItemCode")
                desc = ds.Tables("items").Rows(i).Item("Description")

                newCode.Name = "mnuCode" & i
                newCode.Text = ID
                newCode.Visible = False
                Me.Controls.Add(newCode)

                newbutton.Name = "mnuButton" & i
                newbutton.Text = desc
                newbutton.Size = New Size(150, 100)
                newbutton.BackColor = Color.Orange
                newbutton.ForeColor = Color.White
                newbutton.Font = New Font("Arial", 16, FontStyle.Bold)
                newbutton.TextAlign = ContentAlignment.MiddleCenter
                newbutton.Text = Regex.Unescape(desc)

                newbutton.Top = (150 + (i * 100))
                fPanel.Refresh()

                AddHandler newbutton.Click, AddressOf ButtonClicked
                fPanel.Controls.Add(newbutton)
            Next
        End If
        ds.Reset()
        conn.Close()

    Catch ex As MySqlException

    Finally
        conn.Dispose()
    End Try`

您没有创建多个按钮。您只需不断地反复更改同一按钮上的属性。由于
按钮
是一个实例,因此每次需要新对象实例时都需要调用
New

例如,与此相反:

Dim newbutton As New Button
For i As Integer = 0 To rowscount - 1
    ' ...
    fPanel.Controls.Add(newbutton)
Next
这样做:

For i As Integer = 0 To rowscount - 1
    Dim newbutton As New Button
    ' ...
    fPanel.Controls.Add(newbutton)
Next
或:


如果您发布了一些显示您所做工作的代码,可能会有人更容易帮助您。这可能是因为您设置了
Top
,此时您应该不去管它,让
FLP
完成它的工作。
newCode
newbutton
变量应该在循环中声明,而不是在循环外声明。没有理由调用
fPanel.Refresh
,除非它在添加时不更新-因为它应该更新。就像魔术一样,它工作了。正如您所说,我将变量声明移动到了循环中,就是这样。你真棒!
Dim newbutton As Button = Nothing
For i As Integer = 0 To rowscount - 1
    newbutton = New Button
    ' ...
    fPanel.Controls.Add(newbutton)
Next