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

浪尽此生 提交于 2019-12-01 03:06:22

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

 


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.

If you want to center or use any other alignment style of the Column Header text you can use this

dgvResults.Columns("ColumnName").HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!