2013-05-02 47 views
1

使用VB.NET 2010 /的WinFormsVB.NET「對於每一個」循環無法正常運行

我有一個名爲「Panel1的」面板和麪板內的3個按鍵。在窗體的加載事件,我創建了一個紅色的小廣場,並希望把那個紅色的正方形內各3個按鈕的...

Dim RedSquare As New Panel 
    With RedSquare 
     .Top = 0 
     .Left = 0 
     .Width = 10 
     .Height = 10 
     .BackColor = Color.Red 
    End With 

    For Each Control As Control In Panel1.Controls 
     If TypeOf Control Is Button Then 
      Control.Controls.Add(RedSquare) 
     End If 
    Next 

但是紅色的小廣場僅出現在第一按鈕內。

我在做什麼錯?

回答

4

一個控件只能有一個父對象,所以當你將它添加到第二個按鈕時,它將從第一個對象中移除。如果你想在每個按鈕的紅色方塊,你需要每次創建一個新的

For Each Control As Control In Panel1.Controls 
    If TypeOf Control Is Button Then 
     Dim RedSquare As New Panel 
     With RedSquare 
      .Top = 0 
      .Left = 0 
      .Width = 10 
      .Height = 10 
      .BackColor = Color.Red 
     End With 
     Control.Controls.Add(RedSquare) 
    End If 
Next 
+0

完美,謝謝托馬斯! – NotQuiteThereYet 2013-05-02 00:13:57