在模块中设置datagridview的数据源

时间:2017-10-06 13:46:59

标签: vb.net datagridview

我正在编写一个程序,它将根据一组标准自动处理文件。为了处理这些,我需要先加载Excel文件,然后才能处理它。

我创建了一个名为“NewBusAuto”的模块。在这里,我创建了一个新的datagridview。我正在尝试设置此数据源,但每当我这样做时,它实际上并没有绑定。当我尝试处理每一行/每列时,它说它仍然是空的。

使用的代码:

Module m_NewBusinessAutomation

Dim dgvImport As DataGridView

Public Sub NewBusAuto(ByVal folderName As String,
                      ByVal fileName As String,
                      ByVal executeScript As String)
    dgvImport = New DataGridView

    If Path.GetExtension(fileName) = ".xls" Or Path.GetExtension(fileName) = ".xlsx" Then
        Using cn As New System.Data.OleDb.OleDbConnection
            Dim builder As New OleDbConnectionStringBuilder With _
                {.DataSource = folderName & "\" & fileName,
                 .Provider = "Microsoft.ACE.OLEDB.12.0"}
            builder.Add("Extended Properties", "Excel 12.0; IMEX=1;HDR=Yes;")
            cn.ConnectionString = builder.ConnectionString
            cn.Open()

            Using cmd As OleDbCommand = New OleDbCommand With {.Connection = cn}
                cmd.CommandText = "SELECT * FROM [Sheet1$]"
                Dim dr As System.Data.IDataReader = cmd.ExecuteReader
                Dim dt As New DataTable
                dt.Load(dr)
                dgvImport.DataSource = dt
                dgvImport.Refresh()
                Messagebox.show(dgvImport.RowCount & "-" & dgvImport.ColumnCount)
                dr.Close()
            End Using
        End Using
    End If

结果是消息框给我“0 - 0”。 我需要将Excel文件加载到实际的数据库中。任何帮助将不胜感激!

0 个答案:

没有答案