Reputation: 8636
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?
Upvotes: 4
Views: 23213
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
Upvotes: 2
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
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:
2/ Allow sorting by clicking the checkbox:
3/ After clicking the column:
Upvotes: 13