Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Right Align DataGridView Column Header in Winforms

I have a column Name "Quote Price" in a DataGridView winforms control. I can right align a column with no spaces such as "Unit" howerver I can't right align the column header with column Name called "Quote Price". I have attempted to use the TopRight, MiddleRight and bottomRight with no success.

SelectedAdditionalCost.Columns["Quote Price"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight; // Doesn't want to right align
SelectedAdditionalCost.Columns["Quote Price"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight; // column contents No worries, right aligns.

I am sure I am doing something really silly, however, I can't get this working.

like image 856
Richard Avatar asked Jul 06 '09 07:07

Richard


People also ask

How to set column header alignment in DataGridView vb net?

To change just the one header cell you need to select the column you want from the DataGridView columns collection. dataGridView1. Columns(0). HeaderCell.


1 Answers

As I was writing up the below I realised something that may be the problem - the name of a DataGridView column cannot contain a space - you are referencing the columns collection by the header text, not the column name. Although, when I try and run code like you have in your example I hit a runtime error (null reference exception).

Anyway, that aside:

The code you have works perfectly for me, I implemented the following in one of my datagridview test projects (in the constructor) and the header text right aligns:

dataGridView.Columns[1].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
dataGridView.Columns[2].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;

Because you mentioned the space on the header text, column 2 included a space in its text.

One thing I've seen mentioned is that the header text can appear to not right align when the sort glyph is stopping it from aligning fully to the cell margin.

See if this makes any difference:

dataGridView.Columns[1].SortMode = DataGridViewColumnSortMode.NotSortable;
like image 166
David Hall Avatar answered Sep 24 '22 04:09

David Hall