Nick Manojlovic
Nick Manojlovic

Reputation: 1171

Re-Arrange Panels After Hiding One VB.Net

I have created a windows forms app that is very complex. What I am trying to do now is if different buttons are clicked to disable some panels but shift all the other panels underneath of it up so it looks in order. I am having such a hard time with this. I wanted to develop a function that passes in a Panel that is getting disabled and a list of all other panels underneath of it and using recursion rearrange all the panels. This function works but it does not take in consideration if one panel has a height bigger than the other it leaves extra spaces between the two panels. Any help would be much appreciated.

Public Sub whatever(ByVal panel As Panel, ByVal list As List(Of Panel))
    Dim temppanel As Panel = New Panel()
    For Each item As Panel In list
        temppanel.Location = New Point(temppanel.Location.X, item.Location.Y)
        item.Location = New Point(item.Location.X, panel.Location.Y)
        list.Remove(item)
        whatever(temppanel, list)
        If list.Count = 0 Then
            Exit For
        End If
    Next
End Sub

Image

http://imageshack.us/photo/my-images/268/panelsz.png/

Upvotes: 2

Views: 1845

Answers (1)

LarsTech
LarsTech

Reputation: 81655

A FlowLayoutPanel probably is more appropriate for this, but here is a general method to do what I think you are looking for:

Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) _
                          Handles Button1.Click
  ToggelPanel(Panel2)
End Sub

Private Sub ToggelPanel(ByVal whichPanel As Panel)
  Dim startPoint As New Point(10, 10)
  whichPanel.Visible = Not whichPanel.Visible

  For Each pnl As Panel In Me.Controls.OfType(Of Panel)(). _
                           Where(Function(x) x.Visible). _
                           OrderBy(Function(x) x.TabIndex)
    pnl.Location = startPoint
    startPoint.Y += pnl.Height + 4
  Next
End Sub

Replace Me with the parent container if these panels are not in Me.


If using .net 2.0 where LINQ is not available, the function would look something like this:

Private Shared Function CompareTabIndex(ByVal p1 As Panel, ByVal p2 As Panel) _
                                        As Integer
  Return p1.TabIndex.CompareTo(p2.TabIndex)
End Function

Private Sub ToggelPanel(ByVal whichPanel As Panel)
  Dim startPoint As New Point(10, 10)
  whichPanel.Visible = Not whichPanel.Visible

  Dim panels As New List(Of Panel)
  For i As Integer = 0 To Me.Controls.Count - 1
    If TypeOf Me.Controls(i) Is Panel Then
      If Me.Controls(i).Visible Then
        panels.Add(Me.Controls(i))
      End If
    End If
  Next

  panels.Sort(New Comparison(Of Panel)(AddressOf CompareTabIndex))

  For Each pnl As Panel In panels
    pnl.Location = startPoint
    startPoint.Y += pnl.Height + pnl.Margin.Bottom
  Next
End Sub

Upvotes: 2

Related Questions