Gordon Hepburn
Gordon Hepburn

Reputation: 13

Dynamically Added Controls Do Not Display

I am using the code listing below to dynamically add labels to a new tab page.

    Private Sub PopulateForm(ByVal TabName As String)
    ' This sub will create all of the databound controls on the new tab we have just created.
    'MessageBox.Show(TabName)
    Dim x As Integer = 1
    Dim y As Integer = 10
    Dim NewLabel As Label
    For x = 1 To 243 ' Current number of recipe elements.
        NewLabel = New Label
        NewLabel.Name = "Label" & x
        NewLabel.Location = New Point(10, y)
        NewLabel.Text = "Hello - " & x
        NewLabel.Visible = True
        Me.tabMain.TabPages(TabName).Controls.Add(NewLabel)
        y += 10
    Next
    Me.tabMain.TabPages(TabName).Refresh()
End Sub

My issue is that only the first label is shown on the tab page. None of the others are visible, and by visible i mean i cant see them, you can see I have set the visible property to true!

Please advise...

Upvotes: 0

Views: 48

Answers (1)

Olivier Jacot-Descombes
Olivier Jacot-Descombes

Reputation: 112352

I made a test showing that the labels are indeed added. The problem is that they overlap so that they hide each other's text.

I added this declaration in the form class

Private m_random As New Random()

Then I added this statement to the label creation

NewLabel.BackColor = Color.FromArgb(m_random.Next(255), m_random.Next(255), m_random.Next(255))

The result I got was

enter image description here

My suggestion

y += NewLabel.Height

You might want to arrange your lables in rows and columns. You can do it like this:

Private Sub PopulateForm(ByVal TabName As String)
    Const NumLables = 243
    Const Rows As Integer = 20, ColumnWidth = 65, RowHeight = 20

    For i As Integer = 0 To NumLables - 1
        Dim column = i \ Rows
        Dim row = i Mod Rows
        Dim NewLabel = New Label With {
            .Name = "Label" & i,
            .Location = New Point(10 + column * ColumnWidth, 10 + row * RowHeight),
            .Text = "Hello - " & i,
            .Visible = True,
            .AutoSize = True
        }
        Me.tabMain.TabPages(TabName).Controls.Add(NewLabel)
    Next
End Sub

Upvotes: 2

Related Questions