Search code examples
vb.netwinformsflowlayoutpanel

How to have controls inside Flowlayoutpanel resize and use available space?


I have the following screen:

enter image description here

What I would like to happen is the following:enter image description here

How will it be possible to have the first RichTextBox and the 3rd RichTextBox expand the FlowLayoutPanel when the 2nd "hidden" RichTextBox is set to RichTextbox2.Visible = false.

The idea is to have any of the controls, that are visible inside the FlowLayoutPanel to fill up the space when loading data from the database that is not getting used inside the FlowLayoutPanel as image 2 suggests. So if there is another RichTextBox that all 3 will then occupy all available space inside the FlowLayoutPanel.

I have tried the following suggestions here, but I can't get the expanding unused space right.


Solution

  • Should be fairly simple math... (not going for any efficiency here)

    'assuming you may have a variable number of richtextboxes you need to get a count of the ones that are visible
    'also assuming the richtextboxes are already children of the flowlayoutpanel
    'call this sub after you have put the unsized richtextboxes into the FlowlayoutPanel (assuming you are doing that dynamically)    
    Private Sub SizeTextBoxes()
        Dim Items As Integer = 0
        'create an array for the richtextboxes you will be sizing
        Dim MyTextBoxes() As RichTextBox = Nothing
        For Each Control As Object In FlowLayoutPanel1.Controls
            If TryCast(Control, RichTextBox).Visible Then
                'create a reference to each visible textbox for sizing later
                ReDim Preserve MyTextBoxes(Items)
                MyTextBoxes(Items) = DirectCast(Control, RichTextBox)
                Items += 1
            End If
        Next
    
        'if the flowlayoutpanel doesn't have any richtextboxes in it then MyTextBoxes will be nothing
        If Not IsNothing(MyTextBoxes) Then
            'get the height for the text boxes based on how many there are and the height of the flowlayoutpanel
            Dim BoxHeight As Integer = FlowLayoutPanel1.Height \ Items
            For Each TextBox As RichTextBox In MyTextBoxes
                TextBox.Height = BoxHeight
            Next
        End If
    End Sub
    

    If the number of richtextboxes is indeed variable - you may want to put a limit so you don't wind up with 600 1-pixel high text boxes...