Developer
Developer

Reputation: 8636

Right align a column in datagridview doesn't work

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

I tried this setting for the datagridview 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?

Upvotes: 4

Views: 23213

Answers (3)

daniele3004
daniele3004

Reputation: 13920

For set the the align in column header or in cell content you can use the IDE and open this property mask of dataGridView.

Set the align cell content in Colunm property or set the row header aling in RowHeaderDefaultCellStyle

enter image description here

Upvotes: 2

user6113184
user6113184

Reputation: 1

foreach (DataGridViewColumn col in dataGridView2.Columns){
    col.SortMode = DataGridViewColumnSortMode.NotSortable; // This first set it work
    col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
    col.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}

Upvotes: -1

Chris
Chris

Reputation: 8647

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()
    {
        InitializeComponent();

        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;
        }
        this.DataGridView1.Refresh();
    }
}

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

Upvotes: 13

Related Questions