Search code examples
.netvb.netwinformsflowlayoutpanel

Make FlowLayoutPanel.AutoSize to work with fixed rows or columns


I am creating a left right slider control, by placing a FlowLayoutPanel inside a Panel and set the FlowLayoutPanel.Autosize to true. The Panel size is fixed, these are some properties i set for the FlowLayoutPanel.

FlowDirection = LeftToRight
AutoSize = true
AutoSizeMode = GrowAndShrink
WrapContents = true

At runtime i programatically add buttons to the FlowLayoutPanel which can look like this

enter image description here

The problem is that i wanted to achieve multiple rows by setting a fixed amount of row or columns, but it is always in a single row. That is if i choose say 3 rows, all the buttons will flow in 3 rows only with as many columns as possible or vise versa

pnlSlider.SetFlowBreak(btn,true)

This is what i want to achieve

enter image description here

  • The black box is the panel
  • The brown box the FlowLayoutPanel inside the Panel
  • The green box are the buttons added at runtime

Is there any solution for this

EDIT

I was refered to a solution here Multi-Row Autosize Scrollable FlowLayoutPanel which seems to relate to what I need, but this solution is setting FlowBreaks in designtime, and the amount of rows cannot be fixed.

A sample of what i was trying to replicate. if you look closely, these are buttons place in a panel, most probably a flowlayout sliding inside another control

sliding panel


Solution

  • To have an auto-size, scrollable multi-line FlowLayoutPanel, you can host the FlowLayoutPanel in an auto-scroll panel. Also the FlowLayoutPanel should be auto-size:

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) _
    Handles MyBase.Load
        Me.Size = New Size(320, 160)
        Dim p = New Panel() With {.AutoScroll = True, .Dock = DockStyle.Fill}
        Dim f = New FlowLayoutPanel() With {.AutoSize = True, .WrapContents = True}
        p.Controls.Add(f)
        Me.Controls.Add(p)
        For i = 1 To 20
            Dim btn = New Button() With {.Text = i.ToString()}
            If (i Mod 10 = 5) Then f.SetFlowBreak(btn, True)
            f.Controls.Add(btn)
        Next
        Me.ActiveControl = f.Controls(0)
    End Sub
    

    In above example, I inserted a break on 5th and 15th item to make the result multi-row. Also as you can see, the horizontal scrollbar is visible:

    enter image description here