动态添加的控件不显示

时间:2018-08-18 15:20:33

标签: .net vb.net

我正在使用下面的代码清单向新标签页动态添加标签。

    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

我的问题是,标签页上仅显示第一个标签。其他的都不是可见的,可见的是我看不到它们,您可以看到我将visible属性设置为true!

请告知...

1 个答案:

答案 0 :(得分:2)

我进行了一项测试,表明确实添加了标签。问题在于它们重叠在一起,从而隐藏了彼此的文本。

我在类类中添加了此声明

Private m_random As New Random()

然后我将此语句添加到标签创建

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

我得到的结果是

enter image description here

我的建议

y += NewLabel.Height

您可能希望将标签排列成行和列。您可以这样做:

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