【问题标题】:Which override in Winforms will trigger when data is added to a grid's itemsource?将数据添加到网格的 itemsource 时,Winforms 中的哪个覆盖将触发?
【发布时间】:2016-09-15 16:34:28
【问题描述】:

我目前使用Onload(EventArgs e) 来触发一个函数,该函数将遍历我的数据并根据值更改单元格的颜色,但是当我将数据添加到 DataGridView 的 itemsource 时,我不确定如何调用这个相同的函数。

有满足这种情况的覆盖吗?

我目前用于OnLoad 的示例:

protected override void OnLoad(EventArgs e)
{
    base.OnLoad(e);
    PaintSquares();
}

【问题讨论】:

  • 你不需要在行和单元格之间迭代,使用CellFormatting事件DataGridView就足够了。
  • 我会调查一下,但与此同时,我当前的用例是否有替代方案?
  • 顺便说一句,WinForms 中没有ItemSource,你是在混用 WPF 吗 :)
  • @IvanStoev 我确定,我刚刚从 WPF 切换到 Winforms,很好。

标签: c# winforms datagridview


【解决方案1】:

你不需要在行和单元格之间迭代来格式化它们,使用CellFormattingDataGridView的事件就足够了:

void grid_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
{
    if (e.ColumnIndex < 0 || e.RowIndex < 0)
        return;

    if (string.Format("{0}", e.Value) == "OK")
    {
        e.CellStyle.BackColor = Color.Red;
    }
}

如果您出于任何原因想要使用某些更改事件,则数据源的ListChanged 事件是检测更改发生的合适事件。 BindingSourceBindingList&lt;T&gt;(您正在使用 - 基于您之前的问题)都有 ListChanged 事件。

您还可以依赖DataGridView 事件,例如RowsAddedRowsRemovedCellValueChanged

【讨论】:

  • Welp,你绝对是对的。 CellFormatting 是我一直想要的。再次感谢您!
  • 阅读answer to your previous question 中关于样式单元格的最后一段:动态更改样式的正确方法是什么?看来这篇文章回答了你的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-07
  • 1970-01-01
  • 2019-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多