如何设置TableLayoutPanel单元格的大小

时间:2013-02-04 18:27:01

标签: vb.net

我正在尝试在每个单元格中生成TableLayoutPanel PictureBox + Label。我已经把它做好了,但我不能将单元格大小设置为相同!我正在尝试使用无限行数的4列,并且我希望单元格处于Label宽度,除非Label宽度小于Picture宽度。

现在,我的代码几乎可以工作,它只是没有设置单元格大小,因为我不知道如何做到这一点。

这是我的代码:

 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Dim movieN As Integer = MoviesDataSet.movies.Rows.Count
    Dim tablePanel As New TableLayoutPanel

    With tablePanel
        .Size = New Point(650, 450)
        .ColumnCount = 4
        .GrowStyle = TableLayoutPanelGrowStyle.AddRows
        .AutoScroll = True
        .Margin = New System.Windows.Forms.Padding(0)
        .Location = New System.Drawing.Point(5, 50)
        .CellBorderStyle = TableLayoutPanelCellBorderStyle.Inset
    End With


    For Each MovieRow As DataRow In MoviesDataSet.Tables("movies").Rows
        'define two new controls to be added
        Dim myLabel As New Label
        Dim myPicture As New PictureBox
        Dim container As New Panel

        'set the properties of the new controls
        myLabel.Text = MovieRow("movieName")
        myLabel.Location = New System.Drawing.Point(30, 110)
        With myPicture
            .Image = Image.FromFile(MovieRow("moviePhoto"))
            .Tag = MovieRow("ID")
            .Size = New System.Drawing.Size(100, 100)
            .SizeMode = PictureBoxSizeMode.StretchImage
            .Location = New System.Drawing.Point(2, 2)
        End With

        'here we add the controls to a flow layout panel to
        'manage the positioning of the controls but you could
        'explicitly set the location of the controls if you 
        'just wanted to add them to the forms controls collection
        With container
            .Dock = DockStyle.Fill
            .Margin = New System.Windows.Forms.Padding(0)
            .Controls.Add(myPicture)
            .Controls.Add(myLabel)
        End With


        With tablePanel.Controls
            .Add(container)
        End With

        'here we add a handler for the picture boxs click event
        AddHandler myPicture.Click, AddressOf MyPictureClickEvent
        AddHandler myPicture.MouseHover, AddressOf MyPictureHoverEvent
    Next
    Me.Controls.Add(tablePanel)
End Sub

1 个答案:

答案 0 :(得分:0)

如果您希望单元格宽度与PictureBoxLabel的宽度相同,并且您将它们放在同一单元格中,方法是将它们包装在{{1}中然后将Panel的{​​{3}}属性设置为Panel,将其AutoSizeMode属性设置为AutoSizeMode.GrowAndShrink。如果您对True执行相同的操作,则会根据TableLayoutPanel的大小使每个单元格增大或缩小,Panel将根据内部控制。