Reputation: 2945
I want to make an input box and I have a DataGridView. But it does't work to align the text content of headers or cells.
My code to create DataGridView at runtime:
DataGridView CreateInputBox(int proc,int mac)
{
DataGridView databox = new DataGridView();
for (int i = 0; i < mac; i++)
{
databox.Columns.Add("col" + i, "M" + i);
databox.Columns[i].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
for (int i = 0; i < proc; i++)
{
databox.Rows.Add();
}
databox.AutoSize = true;
databox.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
return databox;
}
The result:
So how can I do the alignment for the header and cells?
Upvotes: 0
Views: 990
Reputation: 51
The code above is only to center the cells foreach column but not the header of each column.
Try to add this line in your "for" :
databox.Columns[i].HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
Src: Changing DataGridView Header Cells' Text Alignment And The Font Size
Upvotes: -1
Reputation: 3871
If I understood correctly, the answer is here: Right align a column in datagridview doesn't work
And the problem is in the Sorting as when it’s enabled the DataGrid reserves some place for a sort glyph. So if you disable the sorting it should work as you expect:
this.DataGridView1.Columns[0].SortMode = DataGridViewColumnSortMode.NotSortable;
Adding this as an answer so everybody who will get here in the future will easily find the way to resolve the problem.
Upvotes: 2