Dotnet Dotnet - 11 months ago 57
C# Question

Right align a column in datagridview doesn't work

I am having a

which is dynamically bound to a
. I would like to align some of the columns in header to right aligned.

I tried this setting for the
for both cellstyle and headercell. For cell style it is showing correctly but for header it is not:

enter image description here

The code I used:

this.dataGridView1.Columns["Quantity"].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
this.dataGridView1.Columns["UnitPrice"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;

Can some one help me?

Answer Source

The code works: the space you see at the right of the header text is "normal".

The DataGridView supports sorting by columns. Therefore, each column header reserves enough space to display the sort glyph (usually an arrow).

If you want the text in column header to be perfectly right aligned, you'll need to disable sorting. Set the SortMode property for the column to NotSortable. This will prevent space from being reserved for the sort glyph.

object lesson:

public class FrmTest : Form

    public FrmTest()

        this.DataGridView1.Columns[0].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleRight;
        this.DataGridView1.Columns[0].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
        this.DataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;

    private void CheckBox1_CheckedChanged(System.Object sender, System.EventArgs e)
        if (this.CheckBox1.Checked) {
            this.DataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.Automatic;
        } else {
            this.DataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;

1/ After loading the form:

enter image description here

2/ Allow sorting by clicking the checkbox:

enter image description here

3/ After clicking the column:

enter image description here