数据表无法正常运行

时间:2013-04-08 14:19:08

标签: vb.net visual-studio-2010 .net-4.0

数据表运行不正常,甚至导致我的动态表格布局无法显示。我完全不知道出了什么问题。顺便说一句,我是初学者。

Public Class ListItem
Dim dt As System.Data.DataTable


Private Sub ListItem_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    Dim conn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source =|DataDirectory|\SMS.accdb"
    Dim sqlstr As String = "Select * from ItemList"
    Dim dtad As New OleDb.OleDbDataAdapter(sqlstr, conn)
    dtad.Fill(dt)
    dtad.Dispose()
End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim ListTable As New TableLayoutPanel()
    ListTable.AutoSize = True
    ListTable.AutoSizeMode = Windows.Forms.AutoSizeMode.GrowAndShrink
    ListTable.Location = New Point(20, 20)
    ListTable.BackColor = Color.White
    ListTable.ColumnCount = CInt(dt.Columns.Count)
    ListTable.RowCount = CInt(dt.Rows.Count)
    ListTable.CellBorderStyle = TableLayoutPanelCellBorderStyle.Single


    For colindex = 0 To dt.Columns.Count - 1
        For rowindex = 0 To 0
            Dim newlabel As New Label()
            newlabel.Location = New Point(10, 10)
            newlabel.Name = "label" & colindex
            newlabel.Font = New Drawing.Font("Microsoft Sans Serif", 16, FontStyle.Underline)
            newlabel.Text = dt.Columns(colindex).ColumnName
            newlabel.AutoSize = True
            ListTable.Controls.Add(newlabel, colindex, rowindex)
        Next
    Next

    Controls.Add(ListTable)
End Sub
End Class

它给了我这个错误:

An unhandled exception of type 'System.NullReferenceException' occurred in StockManagementSystem.exe

Additional information: Object reference not set to an instance of an object.

1 个答案:

答案 0 :(得分:1)

班级内的第一行。改变它:

Dim dt As System.Data.DataTable

到此:

Dim dt As New System.Data.DataTable