在循环中动态生成标签

时间:2015-04-28 19:40:10

标签: arrays vb.net visual-studio loops labels

我遇到了一些问题。当然,我不是最好用VB,但我无法弄清楚为什么这不起作用。

我有一个Access数据库,我从中提取数据。我正在尝试动态创建标签,以便我可以随心所欲地呈现数据。但是,在尝试执行它时,我在行arrayLabels(i).Text = "Howdy"

上遇到异常“System.NullReferenceException:对象引用未设置为对象的实例”

我几乎可以肯定这是一件非常简单的事情,我只是想念......但这是我的代码:

Private Sub TabControl2_Click(sender As Object, e As EventArgs) Handles TabControl2.Click, btnRefresh1.Click, btnRefresh2.Click, btnRefresh3.Click, ddSelectTech.SelectedIndexChanged, ddSelectTech2.SelectedIndexChanged

    If TabControl2.SelectedIndex = 0 Then

        'use this to count the number of rows
        Dim numRows As Integer

        'here be database stuff
        Dim da2 As OleDb.OleDbDataAdapter
        Dim ds2 As New DataSet
        Dim con2 As New OleDb.OleDbConnection
        con2.ConnectionString = dbProvider & dbSource
        sqlStatusOpen = "SELECT * FROM work_orders WHERE status = 'In Progress';"

        da2 = New OleDb.OleDbDataAdapter(sqlStatusOpen, con2)
        con2.Open()
        da2.Fill(ds2, "installations2")
        con2.Close()
        numRows = ds2.Tables("installations2").Rows.Count()

        'create an array label based on the number of rows in the table
        Dim arrayLabels(numRows) As Label

        'loop it to actually make the labels, position them, and such
        For i = 0 To (numRows - 1) 'just looping the number of rows
            Dim x As Integer = 100
            Dim y As Integer = 1 + (i * 10)
            Try
                TabPage3.Controls.Add(arrayLabels(i))
                arrayLabels(i).Text = "Howdy"
                arrayLabels(i).Location = New Point(x, y)
            Catch ex As Exception
                MessageBox.Show(ex.ToString, "Looky there, Franky, another error", MessageBoxButtons.OK, MessageBoxIcon.Error)
            End Try

        Next

    ElseIf TabControl2.SelectedIndex = 1 Then

    ElseIf TabControl2.SelectedIndex = 2 Then

    Else

    End If

End Sub

当然,如果您认为有更好的方法可以解决这个问题,我愿意接受建议。

1 个答案:

答案 0 :(得分:4)

您的代码:

Dim arrayLabels(numRows) As Label

创建类型为Label的数组。但是此数组中的每个条目都是null

尝试初始化循环中的每个标签:

Dim label As New Label
label.Text = "Howdy"
label.Location = New Point(x, y)
TabPage3.Controls.Add(label)

并且您不需要将标签保存在数组中。