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:
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?
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:
2/ Allow sorting by clicking the checkbox:
3/ After clicking the column:
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