Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing DataGridView Header Cells' Text Alignment And The Font Size

Tags:

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.

enter image description here

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?

like image 336
Isuru Avatar asked Oct 19 '12 05:10

Isuru


2 Answers

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()

like image 135
lc. Avatar answered Oct 11 '22 14:10

lc.


or just try this:

dgvBreakDowns.Columns[4].HeaderCell.Style.Alignment = DataGridViewContentAlignment.BottomCenter; 
like image 21
derHippeChip Avatar answered Oct 11 '22 15:10

derHippeChip