datatable的奇怪现象,请高手解答
全局变量
dim dt as new datatable
在Load中设置datagridview的数据源
Private Sub frmExternalCost_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
‘用于检索数据
SelData()
datagridview.DataSource = dt
End Sub
Sub SelData()
dt.Clear()
Dim str As String
str= "select ................... "
dim DBOperate as new Class a '用于检索数据的类
dt = DBOperate.ExecuteSelectSQL(str)
End Sub
class a
Public Function ExecuteSelectSQL(ByVal strSql As String) As DataTable
Dim conn As OleDbConnection
Dim cmd As New OleDbCommand
Dim adp As New OleDb.OleDbDataAdapter
Dim dt As New DataTable
.................. '连接数据库代码
Try
With cmd
.Connection = conn
.CommandText = strSql
End With
With adp
.SelectCommand = cmd
.Fill(dt)
End With
ExecuteSelectSQL = dt
................. '关闭数据库代码
End Function
end class
问题是在Load中第一次调用SelData()没有问题,但我在更新完数据库后再次调用SelData()想刷新dt,datagridview中却不显示一条数据,但dt中是有值的。该现象可能是由于dt.Clear()引起的。但后面我重新检索过了啊。莫非dt.Clear()与dt = DBOperate.ExecuteSelectSQL(str)操作的不是一个datatable?
[解决办法]
不是同一个DataTable,因为你在函数中用了:
Dim dt As New DataTable
你可以把全局的DataTable用Ref传入函数中来达到你的目的,或者每次都绑定新的DataTable