【问题标题】:DataGridView Cell Alignment Won't WorkDataGridView 单元格对齐不起作用
【发布时间】:2012-04-06 09:16:17
【问题描述】:

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

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

如果在 DataBindingComplete 事件期间我执行以下操作,我可以让它工作:

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

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

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

【问题讨论】:

  • 请不要在标题前加上“C#”之类的前缀。这就是标签的用途。

标签: c# winforms datagridview styles alignment


【解决方案1】:

根据MSDNDataGridViewColumnDefaultCellStyle 被通过DataGridView.RowsDefaultCellStyleDataGridView.AlternatingRowsDefaultCellStyleDataGridViewRow.DefaultCellStyleDataGridViewCell.Style 属性指定的样式覆盖。
因此,其中一种样式可能设置为与您所需的对齐方式不兼容的值(例如 DataGridViewContentAlignment.NotSetDataGridViewContentAlignment.TopLeft

【讨论】:

    【解决方案2】:

    关于 DefaultCellStyling 以及继承如何工作的更有用的链接。

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

    原来我设置了一个覆盖 DefaultCellStyle 的 DefaultRowStyle。确保检查所有样式!

    【讨论】:

      猜你喜欢
      • 2014-09-27
      • 1970-01-01
      • 2016-10-05
      • 2011-04-29
      • 2015-04-04
      • 1970-01-01
      • 1970-01-01
      • 2017-07-24
      • 1970-01-01
      相关资源
      最近更新 更多