DataGridView Cell Alignment Won't Work

旧城冷巷雨未停 提交于 2019-12-22 06:59:13

问题


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?


回答1:


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)




回答2:


An even more useful link for DefaultCellStyling and how the inheritance works.

http://msdn.microsoft.com/en-us/library/1yef90x0.aspx

Turned out I had set a DefaultRowStyle that was overriding DefaultCellStyle. Make sure you check all the Styles!!



来源:https://stackoverflow.com/questions/9811641/datagridview-cell-alignment-wont-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!