DataGrid Q&A

I received an e-mail today that contained a question that I've seen posted across several different newsgroups and thought that others would find my response useful.

Q: Is it possible to have a single datagrid split in two parts, with the same vertical scrollbar? If so, how can I create this?

A: You can’t have two different grids in one DataGrid control, but it’s possible to achieve the effect you’re looking for using two DataGrids. You can download the sample solution that I conjured up to demonstrate this.

The ScrollLessDataGrid is a custom grid in which the scroll bars are hidden. Since setting the visibility of the protected scroll bars only hides the scroll bars temporarily, the best way to hide the scroll bars is to just set the width and height of the vertical and horizontal scroll bars respectively to zero. I’ve also added an internal method named UpdateScrollValues that accepts an object of type ScrollData, which is a custom data structure that holds the scroll values. Those values are wrapped up in ScrollEventArgs objects and are used to invoke the GridHScrolled and GridVScrolled methods to update the scroll positions on the grid.

Since there is no way to obtain the scroll bar values outside of the DataGrid, I had to subclass the DataGrid once again. The only thing added to the CustomScrollDataGrid class is an internal property named CurrentScrollValues that returns a ScrollData object containing the current scroll values. Those values are obtained through the value property of the horizontal and vertical scroll bar objects.

On the form, I subscribed to the CustomScrollDataGrid’s Scroll event. Since there’s no way to tell which scroll bar was scrolled, I decided to just store both scroll bar values in a ScrollData object. This object is shipped to the ScrollLessDataGrid by way of the UpdateScrollValues method that I mentioned earlier.