【问题标题】:Dynamically generating labels in loop在循环中动态生成标签
【发布时间】:2015-04-28 19:40:09
【问题描述】:

我有点问题。诚然,我在 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

当然,如果您认为有更好的方法来处理这个问题,我愿意接受建议。

【问题讨论】:

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


    【解决方案1】:

    您的代码:

    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)
    

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

    【讨论】:

    • 事实上,第一个谷歌点击是msdn.microsoft.com/en-us/library/vstudio/…
    • 哦,天哪,我想太多了哔哔声...逻辑超出了我的能力范围。这是那些“努力学习的教训”之一......
    • @jparnell8839,不是将标签的位置放在特定点,而是将它们放在标签页中的FlowLayoutPanel 中?类似FlowLayoutPanel.controls.Add(newLabel)
    猜你喜欢
    • 2012-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-01
    • 2017-12-11
    相关资源
    最近更新 更多