Datagridview ColumnHeader alignment with cell data

612 views Asked by At

picture of the full datagridview

The column header with the number sign has a ridiculous amount of padding.

I've tried messing around with the ColumnHeaderDefaultCellStyle to no avail. Any ideas?

close-up with annotated problem

1

There are 1 answers

3
Ňɏssa Pøngjǣrdenlarp On BEST ANSWER

Okay, if I understand the current form of the question, it goes like this:

enter image description here

Top image BAD - header text does not align with cell text.
Bottom image GOOD: text lines up

First, the header cells have different padding to allow room for the sizer handle and in some cases 3D effects. To get your "title" cells to align with the header, add a little left Padding. To get my "Active" column to line up I used:

dgv1.Columns(3).DefaultCellStyle.Padding = New Padding(2, 0, 0, 0)

For the right aligned header text you may be out of luck, this shows why:

enter image description here

The actual text area of the header cells are restrained to reserve room for the sort glyph. If they didn't do so, the text would jump around as columns are sorted. If you do not intend to let the user sort the data, you can set the column(s) to non sortable and it won't reserve room for the glyph:

dgv1.DataSource = dtSimple
dgv1.Columns(0).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgv1.Columns(0).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
dgv1.Columns(0).SortMode = DataGridViewColumnSortMode.NotSortable

dgv1.Columns(1).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgv1.Columns(1).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
dgv1.Columns(1).SortMode = DataGridViewColumnSortMode.NotSortable

dgv1.Columns(2).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
dgv1.Columns(2).HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight
dgv1.Columns(2).SortMode = DataGridViewColumnSortMode.NotSortable