1
I am suffering to be able to align the header of Datagridview. I want the text to be centered in the center.
Here’s the code:
dg.EnableHeadersVisualStyles = false; // Desabilita formatação padrão
dg.ColumnHeadersDefaultCellStyle.Font = new Font("Arial", 9, FontStyle.Bold);
dg.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
dg.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
dg.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
The result is as in the following figure:
It is aligned in the center, but pulled to the left. Is there a way to put the text 100% centered? I’ve searched the forum but found no one with that problem.
The code is part of a function that receives a Datagridview, formats and returns with the formatting. Follow the complete code:
public DataGridView Grade(DataGridView dg){
dg.EditMode = DataGridViewEditMode.EditProgrammatically;
dg.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dg.AllowUserToAddRows = false;
dg.AllowUserToDeleteRows = false;
dg.DefaultCellStyle.Font = new Font("Calibri", 9);
dg.EnableHeadersVisualStyles = false; // Desabilita formatação padrão
dg.ColumnHeadersDefaultCellStyle.Font = new Font("Arial", 9, FontStyle.Bold);
dg.ColumnHeadersDefaultCellStyle.BackColor = Color.Blue;
dg.ColumnHeadersDefaultCellStyle.ForeColor = Color.White;
dg.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
dg.RowsDefaultCellStyle.BackColor = Color.LightCyan;
dg.AlternatingRowsDefaultCellStyle.BackColor = Color.LightBlue;
dg.MultiSelect = false;
return dg;
}
This function is in the Design class and is called in the others by the code:
public void DataGridViewDesign(){
Design modelo = new Design();
dgDados = modelo.Grade(dgDados);
}
All application Grids look the same.
It is Windows Forms?
– Jéf Bueno
Yes, it’s Windows Forms. I used Visual Studio 2013.
– Lindomar Lemos
@Lindomarlemos Place the section of routine responsible for calling the method
Grade()
also.– gato
I put the code that calls the function. It is the same throughout the application.
– Lindomar Lemos
I’m testing here.
– gato
@Lindomarlemos Adds the line in the method
Grade()
see if it works:dg.RowsDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
– gato
This code is for cell, in it worked leaving the text of the cells aligned to the left and the height centralized. The distance above and below is the same.
– Lindomar Lemos
@Lindomarlemos I made a modification here and solved, left the Header in the center, I will edit my answer.
– gato
Sorry, I put the code in the wrong function. It centralized the cells perfectly the left and right side has the same distance. I just wish the same thing happened to the header.
– Lindomar Lemos