我有一个Form,我必须在其中填充DataGrid。此DataGrid的源代码来自另一个类。
我需要通过Raising Event填充DataGrid,在那个我获得数据的类中。
Imports System.IO
Public Class ExcelReader
Private WithEvents tmrRead As New Timer
Dim fullpath As String = ""
Public Sub ExcelReader()
tmrRead.Interval = 2000
tmrRead.Start()
End Sub
Public Sub TimerTick(ByVal sender As Object, ByVal e As System.EventArgs) Handles tmrRead.Tick
Dim DT As New DataTable
Dim path As String = Directory.GetParent(Directory.GetParent(Directory.GetCurrentDirectory).ToString).ToString + "\ExcelHotReader\"
Dim file1 As String() = System.IO.Directory.GetFiles(path, "*.xls")
Dim file2 As String() = System.IO.Directory.GetFiles(path, "*.xlsx")
If file1.Count <> 0 Or file2.Count <> 0 Then
tmrRead.Stop()
End If
If file1.Count <> 0 Then
fullpath = file1(0).ToString
End If
If file2.Count <> 0 Then
fullpath = file2(0).ToString
End If
Dim DT As New DataTable
Dim cn As System.Data.OleDb.OleDbConnection
Dim cmd As System.Data.OleDb.OleDbDataAdapter
cn = New System.Data.OleDb.OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;" & "data source=" & fullpath & ";Extended Properties=Excel 8.0;")
cmd = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", cn)
cn.Open()
cmd.Fill(DT)
cn.Close()
End Sub
End Class
在cn.Close()之后,应该使用Datatable引发事件。需要通过表单捕获此事件以填充DataGrid。
答案 0 :(得分:2)
在ExcelReader类中添加Event的声明,并使用RaiseEvent在代码的末尾调用它
Public Class ExcelReader
Public Event DataTableLoaded(ByVal dt As DataTable)
.......
Using cn = New System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.12.0;.......")
Using cmd = New System.Data.OleDb.OleDbDataAdapter("select * from [Sheet1$]", cn)
cn.Open()
cmd.Fill(DT)
RaiseEvent DataTableLoaded(DT)
End Using
End Using
....
End Class
然后调用代码使用关键字WithEvents
声明(全局)ExcelReader类的实例Public Dim WithEvents readerTableFromExcel = New ExcelReader()
最后声明处理事件的方法(事件接收器)
Public Sub DataTableFromExcel(ByVal dt As System.Data.DataTable) _
Handles readerTableFromExcel.DataTableLoaded
MsgBox("Table loaded")
End Sub
作为最后一点,我会使用不同的方法来开始阅读Excel文件(例如BackgroundWorker类似乎比TimerTick事件更合适)
如果您需要加深对事件的了解,this article似乎是对重要知识的一个很好的总结