Andrew Florko
Andrew Florko

Reputation: 7750

WinForms: object data source usage best practice

I want to bind list of business objects to Winforms control (DataGridview, ComboBox, e.t.c.).

There are several approaches to do that:

I can create wrapper classes for business objects and override their ToString method implementation. That will work nice for ComboBox, ListBox Items.(Add|AddRange) methods.

But this will not work for DataGridView. It requires ObjectDataSource to tune columns in a designer mode.

As there should be ObjectDataSources (for DataGridViews) and wrapper classes I decided to leave only one approach. The ObjectDataSource one.

Now I have ObjectDataSources for databinding. When I use wizard it adds property to a form that I can use like the following:

MyObjectDataSoure.DataSource = list-of-entities;

That populates underlying winforms control. But I can also assign list of entities directly to datasource property of control and population will be the same.

 MyWinformsControl.DataSource = list-of-entities

Yes, now I am without ObjectDataSource events, but may be there is something more general I miss? Should I avoid listening to winforms events (selection changed, user adding a row) and use object data source ones?

What is the best practice to use object datasources and it's events ?

Thank you in advance!

Upvotes: 3

Views: 4867

Answers (1)

Nicole Calinoiu
Nicole Calinoiu

Reputation: 21002

First of all, do not bind a Window Forms form or control directly to your data objects. There are several known bugs (e.g.: https://connect.microsoft.com/VisualStudio/feedback/details/92260/datagrid-memory-leak-resulted-from-failed-clear-of-databind) involving a failure of the Windows Forms binding mechanism to properly release objects under direct binding. Instead, always bind via a BindingSource, which will allow your objects to be released for garbage collection if they are not in use elsewhere.

As for the rest, I would recommend keeping the binding mechanism as simple as you can overall. If you need to add object data sources for some particular circumstances such as the DataGridView design-time support, do so only for those cases. One of these days, you might end up using an alternate grid control that does not have a similar limitation, and it would be mighty inconvenient to be stuck with an overly complex overall binding pattern just because of a problem that you don't even have anymore.

Upvotes: 5

Related Questions