I have a DataGridView that I use in a C# Winforms project. The grid does NOT autogenerate columns. I have manually set the column names and properties.
This includes the DefaultCellStyle for the cells. I want all cells that are of type DataGridViewCheckBoxColumn to be aligned centered. I have manually set this alignment for each column of this type in the designer. These changes do not show up when the datagridview is loaded.
As my next approach, I used the code below in the DataBindingComplete event (which also had no effect)
foreach (DataGridViewColumn dgvc in this.dgv_Automations.Columns)
{
if(dgvc.CellType == typeof(DataGridViewCheckBoxCell))
dgvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
When debugging, the above code already had the alignment set the center. However, it still does not show up on the grid.
I CAN get it working if during the DataBindingComplete event I do something like this:
foreach (DataGridViewRow dgvr in this.dgv_Automations.Rows)
{
dgvr.Cells["isErrors"].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
However, I have many of these columns and it really doesn't make sense to do it this way. EDIT: I have implemented it this way and with only about 10 rows there is very noticeable lag from setting this property on each cell.
My question is: what is the proper way of doing this? Why does the designer DefaultCellStyle not work?
According to MSDN the DefaultCellStyle
of a DataGridViewColumn
is overridden by the styles specified through the DataGridView.RowsDefaultCellStyle
, DataGridView.AlternatingRowsDefaultCellStyle
, DataGridViewRow.DefaultCellStyle
, and DataGridViewCell.Style
properties.
So it's possibile that one of these styles are set to a value incompatible with your required alignment (for example DataGridViewContentAlignment.NotSet
or DataGridViewContentAlignment.TopLeft
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With