DataGridView 单元格对齐不起作用

2024-02-02

我有一个在 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;
}

调试时,上面的代码已经将对齐设置为中心。然而,它仍然没有出现在网格上。

I CAN如果在 DataBindingComplete 事件期间我执行以下操作,则可以使其正常工作:

foreach (DataGridViewRow dgvr in this.dgv_Automations.Rows)
{
    dgvr.Cells["isErrors"].Style.Alignment = DataGridViewContentAlignment.MiddleCenter;
}

然而,我有很多这样的专栏,这样做确实没有意义。编辑:我已经通过这种方式实现了它,并且只有大约 10 行,在每个单元格上设置此属性有非常明显的滞后。

我的问题是:这样做的正确方法是什么?为什么设计器 DefaultCellStyle 不起作用?


根据MSDN http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.defaultcellstyle.aspx the DefaultCellStyle of a DataGridViewColumn被通过指定的样式覆盖DataGridView.RowsDefaultCellStyle, DataGridView.AlternatingRowsDefaultCellStyle, DataGridViewRow.DefaultCellStyle, and DataGridViewCell.Style特性。
因此,这些样式之一可能被设置为与您所需的对齐方式不兼容的值(例如DataGridViewContentAlignment.NotSet or DataGridViewContentAlignment.TopLeft)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

DataGridView 单元格对齐不起作用 的相关文章

随机推荐