Wednesday, January 24, 2007

DataGridView and unbounded mode

New DataGridView control in .NET 2.0 is a complex and very useful control. Grids are generally very useful for displaying large amount of data in a constrained screen space.

Like many other Windows Forms controls, DataGridView can operate in a data bound or unbounded mode. When unbound, client can manipulate rows and cells directly, while in data bound mode control operates according to a well-known Model-View paradigm, where changes to data (model) are automatically reflected by the control (view).

In my case, view did not map directly to the data I was trying to show in DataGridView, and so initially I opted for unbounded mode. I was trying to implement hierarchical views (which are unsupported by default in DataGridView), and also mix and match data types that appear in grid's rows. And so unbounded mode seemed like a good idea.

Not less than a week into implementation I have discovered that operating in this mode is insufficient for my needs. For one, I could not detect an event before a row is deleted, only after deletion took place. Since I was storing helper objects in the row's Tag property, I was not able to run special code on row deletions. In addition, because I was operating on DataGridView directly, it meant that my row-handler objects had to operate on the grid directly, which creates somewhat inter-dependent code (model that knows about view!).

The point of this post is that I switched back to data bound mode and never looked back (although it tooks some time to refactor existing code)! The key to making this work is to make an intermediary model, which models the rows in the grid. I made a class that inherits from BindingList and made it responsible for manipulating row-handler objects. Then DataGridView can be bound to that list, and all changes in the list are reflected in the grid.

No comments: