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?
Ah, got it!
DataGridView1.DataSource = Bds.DataSource
I guess using = Bds just creates a reference but = Bds.DataSource does not.
Disposing the BindingSource does not cause problems this way.