vb.net对象变量或未设置块变量,OleDbDataReader

时间:2012-08-08 04:17:30

标签: vb.net

我正在尝试使用vb.net将mdb写入CVS转换器。 我想使用oledbdata阅读器获取列标题名称,到目前为止这是我的代码

 Public Cheadernames As Array
    Public firstRead As Boolean = False
    Public columnCount

    Dim connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strfilename
    Dim queryString = "SELECT * FROM products"
    Dim connection As New OleDbConnection(connectionstring)
    Dim command As New OleDbCommand(queryString, connection)
    connection.Open()
    Dim reader As OleDbDataReader = command.ExecuteReader()
    While reader.Read
        If firstRead Then
            columnCount = reader.FieldCount()
            firstRead = False
            For i = 0 To columnCount - 1
                Cheadernames(i) = reader.GetName(i) ' i am getting an error with this line
                Console.WriteLine(Cheadernames(i))
            Next
        End If

所以我试图将所有列标题名称放在一个数组中但是注释行给了我这个错误“对象变量或者没有设置块变量”

1 个答案:

答案 0 :(得分:3)

您的Cheadernames变量是一个空数组,没有元素也没有类型。这是错的:你几乎不应该声明一个变量或方法参数“As Array”。相反,你想要这样的东西:

Private HeaderHames() As String
Private firstRead As Boolean = True
Private columnCount As Integer

Dim connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strfilename
Dim queryString = "SELECT * FROM products"
Using connection As New OleDbConnection(connectionstring), _ 
      command As New OleDbCommand(queryString, connection)

    connection.Open()
    Using reader As OleDbDataReader = command.ExecuteReader()
        While reader.Read
            If firstRead Then
                columnCount = reader.FieldCount()
                HeaderNames = New String(columnCount-1)
                firstRead = False
                For i = 0 To columnCount - 1
                    HeaderNames(i) = reader.GetName(i) 
                    Console.WriteLine(HeaderNames(i))
                Next
            End If
            '...
         End While
     End Using
 End Using