Question

I've been trying to add items to my tableLayoutPanel in visual studio .net application, but it seems that they just get replaced in the first item position.

Public rows As Integer = 0
Public CAIList As New List(Of String)
Public p As New Panel()
Public p2 As New Panel()
Public tb As New Label()
Public tb2 As New Label()
Public Sub addCAI()    
If Not String.IsNullOrWhiteSpace(txt_analyst.Text) Then
  CAIList.Add(txt_analyst.Text)
  tb.Text = txt_analyst.Text
  tb2.Text = "OUTDATED"
  p.Controls.Add(tb)
  p2.Controls.Add(tb2)
  p.AutoSize = True
  p2.AutoSize = True
  MainMenu.table_analysts.Controls.Add(p, 0, rows)
  MainMenu.table_analysts.Controls.Add(p2, 1, rows)
  rows = rows + 1
Else
   MessageBox.Show("Cannot add empty Analyst")
End If

At first I thought that the problem was that "Rows" kept being set to 0, but then I debugged it and it increments alright. (0,1,2,3....)

IT SHOULD WORK!!! it's driving me crazy.

Was it helpful?

Solution

It's not clear from the post how many rows are in your TableLayoutPanel, but you have to make sure the rows exist in order to add those controls. I don't think an exception is thrown when trying to add controls to a non-existent cell:

If MainMenu.table_analysts.RowStyles.Count - 1 < rows Then
  MainMenu.table_analysts.RowStyles.Add(New RowStyle(SizeType.Percent))
End If

For i As Integer = 0 to rows
  MainMenu.table_analysts.RowStyles(i).Height = 1 / rows
Next

MainMenu.table_analysts.Controls.Add(p, 0, rows)
MainMenu.table_analysts.Controls.Add(p2, 1, rows)
rows = rows + 1

Also, make sure the cells are empty before adding the panels by disposing any existing controls. Only one control is allowed per cell.

As Idle_Mind commented, make sure you also create "new" controls when you call your routine:

Public Sub addCAI()
  If Not String.IsNullOrWhiteSpace(txt_analyst.Text) Then
    Dim p As New Panel()
    Dim p2 As New Panel()
    Dim tb As New Label()
    Dim tb2 As New Label()
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top