1

Using VB.NET 2010 / WinForms

I have a panel named "Panel1", and 3 buttons inside that panel. In the form's load event, I am creating a small red square, and want to put that red square inside each of the 3 buttons...

    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

But the small red square only appears inside the 1st button.

What am I doing wrong?

4

1 回答 1

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
于 2013-05-02T00:11:09.643 回答