How can I center the heading in a column on a DataGridView?

Keith picture Keith · Dec 29, 2010 · Viewed 31.1k times · Source

I have a strange problem and it's probably a simple fix, but after much research, I cannot seem to find a solution.

I have a DataGridView on which I'm trying to center the column headings, but the result is a left bias in the centering—almost like an indenting problem. I've seen a few posts on this issue on a site or two, but never a solution. Any thoughts?

Here's the statement I'm currently trying to use:

DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

Answer

Cody Gray picture Cody Gray · Dec 29, 2010

The code you've posted is on the right track: you need to set the ColumnHeadersDefaultCellStyle property of your DataGridView control.

However, you need to create a new DataGridViewCellStyle class and assign that to the ColumnHeadersDefaultCellStyle property. You can't modify the Alignment property as your code sample shows unless you have assigned a DataGridViewCellStyle class to this property.

So, for example, the following code achieves perfectly centered column headings in a blank project:

Dim dgvColumnHeaderStyle As New DataGridViewCellStyle()
dgvColumnHeaderStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

myDataGridView.ColumnHeadersDefaultCellStyle = dgvColumnHeaderStyle

 DataGridView with centered column headings


In the future, you may find it easier to do these types of things from the Designer. If you still need to do it yourself through code, you can check the *.Designer.vb file that is created to see how it was done.


EDIT: I just now noticed the slight offset you're referring to in the columns—it does indeed create a little extra padding to the right of each header. It's not a bug, though. There's a much simpler explanation.

Like a ListView, the DataGridView supports sorting by columns. Therefore, each column header reserves enough space to display the sort glyph (usually an arrow) when calculating center justification.

If you want the column headers to be perfectly centered, you'll need to disable sorting. Set the SortMode property for the column to "NonSortable". This should prevent space from being reserved for the sort glyph whenever the column text is center or right justified.