我有一个在C#Winforms项目中使用的DataGridView。网格不会自动生成列。我已手动设置列名称和属性。
这包括单元格的DefaultCellStyle。我希望所有类型为DataGridViewCheckBoxColumn的单元格都居中对齐。我已在设计器中为此类型的每个列手动设置此对齐方式。加载datagridview时,这些更改不会显示。
作为我的下一个方法,我在DataBindingComplete事件中使用了下面的代码(也没有效果)
foreach (DataGridViewColumn dgvc in this.dgv_Automations.Columns)
{
if(dgvc.CellType == typeof(DataGridViewCheckBoxCell))
dgvc.DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
调试时,上面的代码已经将对齐设置为中心。但是,它仍然没有显示在网格上。
我 CAN 如果在DataBindingComplete事件中我做了类似这样的事情,它就能正常工作:
foreach (DataGridViewRow dgvr in this.dgv_Automations.Rows)
{
dgvr.Cells["isErrors"].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
}
但是,我有很多这样的列,这样做真的没有意义。编辑:我已经用这种方式实现了它,只有大约10行,在每个单元格上设置这个属性会有非常明显的延迟。
我的问题是:这样做的正确方法是什么?为什么设计师DefaultCellStyle不起作用?
答案 0 :(得分:7)
根据MSDN,DefaultCellStyle
的{{1}}会被DataGridViewColumn
,DataGridView.RowsDefaultCellStyle
,DataGridView.AlternatingRowsDefaultCellStyle
指定的样式覆盖,并且DataGridViewRow.DefaultCellStyle
属性。
因此,可能会将其中一个样式设置为与您所需的对齐方式不兼容的值(例如DataGridViewCell.Style
或DataGridViewContentAlignment.NotSet
)
答案 1 :(得分:0)
DefaultCellStyling的一个更有用的链接以及继承的工作原理。
http://msdn.microsoft.com/en-us/library/1yef90x0.aspx
原来我设置了一个覆盖DefaultCellStyle的DefaultRowStyle。确保检查所有样式!!