Changing DataGridView Header Cells' Text Alignment And The Font Size
c#, datagridview
Solution
Try this (note I'm using Columns here and not Rows):
foreach(DataGridViewColumn col in dgvBreakDowns.Columns)
{
col.HeaderCell.Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
col.HeaderCell.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel);
}
As for deselecting the cell, try `dgvBreakDowns.ClearSelection()`
Problem
I'm trying to change the text alignment and the font size of a DataGridView. All the Columns are created programatically at runtime. Here's the code.. ``` private void LoadData() { dgvBreakDowns.ColumnCount = 5; dgvBreakDowns.Columns[0].Name = "Breakdown No"; dgvBreakDowns.Columns[1].Name = "Breakdown Type"; dgvBreakDowns.Columns[2].Name = "Machine Type"; dgvBreakDowns.Columns[3].Name = "Date"; dgvBreakDowns.Columns[4].Name = "Completed"; dgvBreakDowns.Columns[4].Visible = false; foreach (DataGridViewHeaderCell header in dgvBreakDowns.Rows) { header.Style.Alignment = DataGridViewContentAlignment.MiddleCenter; header.Style.Font = new Font("Arial", 12F, FontStyle.Bold, GraphicsUnit.Pixel); } } ``` This `LoadData()` method is called in the Form's constructor. The Columns are created but their Headers' changes don't apply. I think its because of a flaw in my loop `foreach (DataGridViewHeaderCell header in dgvBreakDowns.Rows)?` I'm not sure. I tried changing it to `dgvBreakDowns.Columns` and I get an InvalidCastException. How can I select the Header Cells to apply those changes? I have another minor issue. When I run the program it looks like this. Notice the first Cell is selected by default therefore it appears Blue. Sure it doesn't affect anything but it just looks somewhat ugly and untidy. It is possible to stop it from selecting the Cell like that?