Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 230
Developer Avatar asked Dec 08 '22 14:12

Developer


1 Answers

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

like image 112
Chris Avatar answered Dec 11 '22 08:12

Chris