【问题标题】:Slow performance while setting some rows in bold in datagridview在 datagridview 中以粗体设置某些行时性能降低
【发布时间】:2013-04-04 07:33:49
【问题描述】:

我正在尝试在 datagridview 中以粗体显示某些行。这在 datagridview 的绑定完成时应用。

Font bold = new System.Drawing.Font(this.GridView.Font, FontStyle.Bold);

foreach (DataGridViewRow row in this.GridView.Rows)
{
    FlattenedResult item = row.DataBoundItem as FlattenedResult;
    if(item != null)
    {
        if(item.ParentID.Equals(item.ID))
        {
            row.DefaultCellStyle.Font = bold;
         }
     }
 }

问题是此操作需要超过 9 分钟(仅适用于 1000 行...)。有没有更好的办法?

谢谢!

【问题讨论】:

  • 你应该看看虚拟模式。
  • 不要循环遍历datagridview,而是尝试使用datatable.select从datagridview数据源中选择要加粗的行的索引,然后使用该索引设置粗体
  • 先过滤父行,只迭代父行来设置样式

标签: c# winforms datagridview


【解决方案1】:

我曾经和你做同样的事情,10 行需要 0.050 秒才能完成。

根据Cell Styles in the Windows Forms DataGridView Control,行/单元格Style 属性在您每次调用getter 时都会实例化一个新的DataGridViewCellStyle(您需要做什么才能设置Font 属性)。

只创建一次新的DataGridViewCellStyle 对我来说提高了十倍的性能。使用以下代码,完成需要 0.005 秒。

private void dataGridView_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    DataGridViewCellStyle style = new DataGridViewCellStyle(this.DataGridView.RowsDefaultCellStyle);
    style.Font = new System.Drawing.Font(this.DataGridView.Font, FontStyle.Bold);

    foreach (DataGridViewRow row in this.DataGridView.Rows)
    {
        FlattenedResult item = row.DataBoundItem as FlattenedResult;

        if (item != null)
        {
            if (item.ParentID.Equals(item.ID))
                row.DefaultCellStyle = style;
        }
    }
}

您还可以使用e.ListChangedType 属性过滤DataBindingComplete 类型。

这可能不是更好的解决方案,但我希望它有助于找到它。

您还可以查看共享行,但它似乎只适用于无用户交互的 DataGridView。

【讨论】:

    【解决方案2】:

    问题可能是由您的网格属性引起的。就我而言,我已将属性设置为

    AutoSizeColumnsMode=AllCells
    

    可能在单元格格式化后,列和标题单元格中的所有其他单元格必须重新绘制以使其尺寸适合新的单元格尺寸。在我将属性值更改为默认值"None" 后,立即绘制网格。

    【讨论】:

      【解决方案3】:

      1) 按照 Aphelion 的建议,使用虚拟模式 dataGridView1.VirtualMode = true。您可以在此处查看示例DataGridView live display of datatable using virtual mode

      2) 使用属性 ShouldBeInBold 准备数据源行(找到有意义的名称)。 并在CellValueNeeded事件订阅者中使用。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-01-28
        • 2018-12-28
        • 1970-01-01
        • 2021-04-05
        • 2023-03-05
        相关资源
        最近更新 更多