2015-04-03 44 views
0

我正在使用VS 2012(vb.net),并且我有一个包含未知数量按钮的flowLayoutPanel的窗体。简单来说,基本上,当表单Loads I基于一个条件从表中获取项目,然后使用For ... Next块将每个项目的按钮添加到flowLayoutPanel时。所以,如果我找到5个项目,我添加5个按钮,所有命名不同,但问题是,他们似乎堆积在彼此,而不是很好地排队。当我使用按钮来逐个添加项目时,它可以正常工作,但是当我使用For ... Next块时,它不起作用。我已经尝试在添加每个按钮后刷新flowLayoutPanel,我试图设置每个新按钮相对于上一个按钮位置的位置,但它仍然可以工作。 我已经研究了一个多星期,现在有很多东西,但没有具体处理这件事。添加到FlowLayoutPanel的按钮堆积在彼此之上

感谢您的帮助。

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

`再 如果conn.State <> ConnectionState.Open然后 conn.Open() 结束如果

 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` 
+0

它可能是e如果你发布了一些代码来显示你已经完成了什么,那么你就可以帮助你。 – 2015-04-03 13:24:51

+0

这可能是由于你设置了“顶部”,当你应该离开它,让'FLP'做它的工作。 'newCode'和'newbutton'变量应该在循环中声明,而不是在它之外。没有理由调用'fPanel.Refresh',除非它在添加时不更新 - 因为它应该。 – OneFineDay 2015-04-03 13:37:29

+0

就像魔术一样。我像你所说的那样将变量声明移动到循环中,就是这样。你太棒了! – 2015-04-03 13:41:36

回答

0

没有创建多个按钮。你只需不断地改变同一个按钮上的属性。由于Buttonreference type,你需要调用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 

或者:

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