Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct way to unbind a BindingSource from a DataGridView

I have a BindingList<> of objects, set to the DataSource of a BindingSource. This is set to the DataSource of a DataGridView.

I'm concerned with not causing any potential memory leaks, so wondering if there is a preferred way to unbind these connections when I am finished with the data.

I'm thinking of:

datagridview.DataSource = null;
bindingsource.DataSource = null;
bindingsource.Clear();

To re-bind:

bindingsource.DataSource = bindinglist<myObjects>;
datagridview.DataSource = bindingsource;

Is this order correct, or does it really matter? Have I omitted anything which should be there?

like image 321
Andy Avatar asked Oct 10 '09 09:10

Andy


2 Answers

Assigning null to the datagridview DataSource is the best way to clear data source of grid, you are correct.

like image 82
Wael Dalloul Avatar answered Sep 24 '22 08:09

Wael Dalloul


If you use custom columns, set AutoGenerateColumns to false before clearing the DataSource. This will ensure your custom columns are preserved. Otherwise they will be cleared and auto generated on the next DataBind.

datagridview.AutoGenerateColumns = false; 
datagridview.DataSource = null;

Edit: Not sure why this was down voted. This is the correct solution for non auto generated columns. I have the project to prove it. I hope someone finds it useful.

like image 40
Tomas Beblar Avatar answered Sep 24 '22 08:09

Tomas Beblar