DataGrid Q&A #2

Q: How do I extend the DataGrid's furthest right column so that the column (or, at least, the column header) extends all the way to the right edge of the grid when the furthest right column is visible?

A: In all of my articles on the Windows Forms DataGrid control, I’ve emphasized that the key to getting the DataGrid to render the way you want it to lies in its styles. I've uploaded a zip file containing a solution that demonstrates how to do several different things:

  1. Use reflection to retrieve a reference to the default table style.
  2. Iterate over the default column style collection to calculate the widths of the columns.
  3. Calculate the width necessary for the rightmost column to span the remaining area of the visible grid.
  4. Ensure that when columns are resized, the desired stretching effect remains intact unless the resize would force the rightmost column to shrink under its defined width.
  5. Seamlessly handle the OnSizeChanged event.

The project has two files of interest: Form1.cs and MyCustomDataGrid.cs. The latter has all of the code that you’re going to be interested in. I’ve provided a fair amount of inline comments, but if there is any ambiguity, please feel free to let me know.

EDIT: The solution has been updated to include functionality to support column resizing when double clicking on column borders.