Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 550
Keith Avatar asked Dec 29 '10 01:12

Keith


People also ask

How do I center text in GridView header?

or just use this style, that select the of the specific table (select by table's class). <style> table. table_class tbody tr th { text-align:center ! important; } </style> <asp:GridView runat="server" ID="Gv_Data" CssClass="table_class " ...


1 Answers

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.

like image 170
Cody Gray Avatar answered Nov 02 '22 08:11

Cody Gray