On Form_load three labels are inserted dynamically to the TableLayoutPanel.On clicking the first label, two labels popup as submenus. Now my isuue is, on clicking the second label, its submenu labels are appearing under the first label instead of second label. Where might be the problem?

Public Class Form1

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim objLbl As Label

TableLayoutPanel1.RowCount = 0
For i As Integer = 0 To 2
TableLayoutPanel1.RowStyles.Add(New System.Windows.Forms.RowStyle(SizeType.AutoSize, 20))
TableLayoutPanel1.RowCount += 1
objLbl = New Label
objLbl.Font = New Drawing.Font("Segoe UI", 12, FontStyle.Regular)
objLbl.Text = "Label: " + i.ToString()
TableLayoutPanel1.Controls.Add(objLbl, 0, i)
AddHandler objLbl.Click, AddressOf objLbl_Click
End Sub

Private Sub objLbl_Click(ByVal sender As Object, ByVal e As System.EventArgs)
Dim objLbl As Label
Dim tempHolding As New List(Of HoldingCell)
Dim cell As HoldingCell
Dim intPosition As Integer

intPosition = TableLayoutPanel1.GetRow(sender)
With TableLayoutPanel1
For row As Int32 = intPosition To TableLayoutPanel1.RowCount - 1
For col As Int32 = 0 To TableLayoutPanel1.ColumnCount - 1
cell = New HoldingCell
cell.cntrl = .GetControlFromPosition(col, row)
'setup position for restore = current row + 1 
cell.pos = New TableLayoutPanelCellPosition(col, row + 1)
Next col
Next row

'insert new row 
For intRow = 0 To 1
.RowStyles.Insert(intPosition, New RowStyle(SizeType.Absolute, 20.0!))
.RowCount += 1

'adjust control positions 
For Each cell In tempHolding
If cell.cntrl IsNot Nothing Then
.SetCellPosition(cell.cntrl, cell.pos)
End If
Next cell

'add controls to the inserted row
For intRow = 0 To 1
objLbl = New Label
objLbl.Text = Space(5) & "sub label " & intRow
TableLayoutPanel1.Controls.Add(objLbl, 0, intPosition)
End With
End Sub

Structure HoldingCell
Dim cntrl As Control
Dim pos As TableLayoutPanelCellPosition
End Structure
End Class

found the solution.just add

'Shift exist controls down
          For Each ExistControl As Control In TableLayoutPanel1.Controls
              If TableLayoutPanel1.GetRow(ExistControl) >= intPosition Then
                  TableLayoutPanel1.SetRow(ExistControl, TableLayoutPanel1.GetRow(ExistControl) + 1)
              End If


'adjust control positions

part of the code.


This article has been dead for over six months. Start a new discussion instead.