处置 BindingSource 会破坏 DataGridView 数据源
简介:如果我在将 BindingSource 分配给 DataGridView.DataSource 后不处理它,我的代码就可以工作,但如果我处理它,它就会中断 - 为什么?我需要担心如何处置它吗?
Public Sub GridViewUpdate()
Dim cn As New System.Data.SqlServerCe.SqlCeConnection
Dim SQL As System.Data.SqlServerCe.SqlCeCommand
Dim tbl As New DataTable
Dim adp As System.Data.SqlServerCe.SqlCeDataAdapter
Dim Bds As New BindingSource
DataGridView1.Columns.Clear()
cn.ConnectionString = "Data Source = C:\path\data.sdf"
SQL = cn.CreateCommand
SQL.CommandText = "SELECT myfields FROM myTable ORDER BY field1 DESC, field2 ASC"
cn.Open()
adp = New SqlServerCe.SqlCeDataAdapter(SQL)
adp.Fill(tbl)
Bds.DataSource = tbl
DataGridView1.DataSource = Bds
cn.Close()
cn.Dispose()
SQL.Dispose()
adp.Dispose()
tbl.Dispose()
Bds.Dispose() '*** <<--- This breaks it - GridView becomes empty
End Sub
那么,这是怎么回事?当我设置 DataGridView1.DataSource = Bds 时,它只是将其作为参考吗?程序退出后Bds如何被释放?如果我向 DataGridView1.DataSource 分配其他内容,垃圾收集会拾取它吗?我需要担心这个吗?
Brief : I have code which works if I don't dispose of the BindingSource after it has been assigned to DataGridView.DataSource but breaks if I do dispose it - why? Do I need to worry about disposing this?
Public Sub GridViewUpdate()
Dim cn As New System.Data.SqlServerCe.SqlCeConnection
Dim SQL As System.Data.SqlServerCe.SqlCeCommand
Dim tbl As New DataTable
Dim adp As System.Data.SqlServerCe.SqlCeDataAdapter
Dim Bds As New BindingSource
DataGridView1.Columns.Clear()
cn.ConnectionString = "Data Source = C:\path\data.sdf"
SQL = cn.CreateCommand
SQL.CommandText = "SELECT myfields FROM myTable ORDER BY field1 DESC, field2 ASC"
cn.Open()
adp = New SqlServerCe.SqlCeDataAdapter(SQL)
adp.Fill(tbl)
Bds.DataSource = tbl
DataGridView1.DataSource = Bds
cn.Close()
cn.Dispose()
SQL.Dispose()
adp.Dispose()
tbl.Dispose()
Bds.Dispose() '*** <<--- This breaks it - GridView becomes empty
End Sub
So, what is going on here? When I set DataGridView1.DataSource = Bds does it just do this as a reference? How does Bds get disposed once the procedure exits? Does garbage collection pick it up if I assign something else to DataGridView1.DataSource? Do I need to worry about this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

是的,数据源引用了您的数据表。
试试吧
Yes the datasource is referenced to your Datatable.
Just try