I'm finally getting around to learning about the BindingSource object -- good stuff. So, this type of code is a common way to load a DataGridView now:
DataTable dtInv = new DataTable();
// Do whatever populates dtinv...
bsData.DataSource = null;
bsData.DataSource = dtInv;
dgv.DataSource = bsData;
Works fine, and I am able to access the BindingSource's DataRowViews as well as the DataRows underlying those. Cool.
I am wondering about the scope of the underlying DataTable object, though. I used to have dtInv declared as a form-level data member, so I expected everything to work fine when the data behind the BindingSource was accessed from other methods. But it works even when the underlying DataTable is local only to the data-loading method.
So, does a BindingSource object clone the entire DataTable? If I do use a form-level data member for the DataTable, will the BindingSource use a reference to it instead of creating a separate copy of the data? I think I have tested that but am not sure of the results... When I use a form-level DataTable, if I clear/null it out while the Binding ource is displaying its data in the grid, I'll get a null exception if I try to access a DataRow underlying one of the BindingSource's DataRowView objects.
I can't seem to find a definitive answer on this (feel free to point me somewhere that explains this in detail), but the following seems to be the case:
- If a BindingSource has its DataSource property set to a object that subsequently goes out of scope, the BindingSource keeps the underlying object "alive", accessible, and in its entirety.
- If the BindingSource has its DataSource property set to an object that remains in scope, it will keep pointing to that as long as it can.
Or, to put it another way, a BindingSource will pull in and keep its underlying data persistent if it needs to (e.g. the underlying object is destroyed/disposed/goes out of scope).
Yes? No? Like I said, I'd appreciate someone "teaching me how to fish" on this one, I just haven't been able to find a discussion about it (or don't know where to read more deeply about it to find one).
dtInvso it will keepdtInvalive even when the variabledtInvgoes out of scope. This isn't anything magic. This is exactly that same as if you'd assigndtInvto a class property or field. - Matt Burland