VB.NET使用索引标签添加TabPage

时间:2017-12-06 01:44:26

标签: vb.net loops tabpage

你想要完成什么?

我想将TabPage添加到预先存在的TabControl,其中Label具有索引名称。

    Private Sub BtnAddReport_Click(sender As Object, e As EventArgs) Handles BtnAddReport.Click

    Dim rep As New OpenFileDialog
    rep.Title = "Add Report"
    rep.InitialDirectory = "C:\Customers"
    rep.FileName = ""
    rep.DefaultExt = ".html"
    rep.Filter = "HTML Documents|*.html"
    rep.Multiselect = False
    If rep.ShowDialog() = DialogResult.OK Then

        Dim newTab As TabPage = New TabPage With {.Text = Path.GetFileName(rep.FileName)}
        TabControl2.Controls.Add(newTab)

        Dim i As Integer
        For i = 1 To TabControl2.TabPages.Count
            Dim lbl As Label = New Label With {.Text = "Label" & i, .Location = New Point(3, 3)}
            newTab.Controls.Add(lbl)
        Next

    End If

End Sub

您对结果的期望是什么?

每次单击该按钮时,都会添加一个新标签,其标签名为“Label1”,“Label2”等。

您获得的实际结果是什么?

此代码会创建一个新的标签页并添加标签,但它始终以Label1命名,并且不会增加1.

1 个答案:

答案 0 :(得分:1)

为什么在那里有For循环?你只想添加一个Label,对吧?您应该创建一个TabPage,创建一个Label,将Label添加到TabPage,然后将TabPage添加到TabControl

Dim newTab As TabPage = New TabPage With {.Text = Path.GetFileName(rep.FileName)}
Dim lbl As Label = New Label With {.Text = "Label" & (TabControl2.TabPages.Count + 1), .Location = New Point(3, 3)}

newTab.Controls.Add(lbl)
TabControl2.TabPages.Add(newTab)