Click here to Skip to main content
15,936,758 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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.

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

1 solution

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.

Share this answer

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900