Disabled Scrollbars in WinForms DataGrids

by bob on March 11, 2007

I had a WinForms DataGrid about 10 rows high whose DataSource was a DataTable of perhaps a hundred rows — yet, the vertical scrollbar was initially disabled until I sorted or resized a column. A quick web search reveals that this has been encountered by others before, at least in the 1.1 framework. I can’t find an official Microsoft document on it and no one seems to have a cause. Most people report issues with the vertical scrollbar but some also mention problems with the horizontal scrollbar.

If this one bites you, there are some solutions.

One workaround that you can put at the end of the form Load event tweaks the width of the first column, then puts it back:

C#:

DataGridColumnStyle col1 = myDataGrid.TableStyles[0].GridColumnStyles[0];
col1.Width++;
col1.Width--;

VB.NET:

With myDataGrid.TableStyles(0).GridColumnStyles(0)
  .Width += 1
  .Width -= 1
End With

Someone else suggested an inherently fragile solution: the first two controls in the DataGrid’s Controls collection are the horizontal and vertical scrollbars, respectively. Simply set the Enabled property of the desired scrollbar to true. Unfortunately, nothing says that these controls will always be in those locations, and since it’s undocumented, it can always change in future versions of the framework, if nothing else. You could write code to locate the scrollbars by name or type, but it seems like more trouble and slower performance than the Width-tweaking solution above.

Another possibility is to subclass the DataGrid and use the subclass to surface the Enabled properties of the scrollbars via the protected VertScrollBar and HorizScrollBar properties of the DataGrid class.

In my view, the Width-tweaking solution still wins out, though, because manipulating the Enabled property of scrollbars runs the risk of enabling the scrollbars when they don’t need to be — when the grid isn’t full. It’s always dangerous to make assumptions about runtime conditions, now or in the future.

{ 1 comment… read it below or add one }

Rod Kuhns May 5, 2007 at 4:11 pm

Thank you for posting this work around! Exactly what I was trying to figure out and your solution worked like a charm!

Leave a Comment

Previous post:

Next post: