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.
To change just the one header cell you need to select the column you want from the DataGridView columns collection. dataGridView1. Columns(0). HeaderCell.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With