【问题标题】:DataGridView.CellValueChanged not firing for data-bound DataGridViewDataGridView.CellValueChanged 未触发数据绑定 DataGridView
【发布时间】:2015-10-16 12:17:30
【问题描述】:

虽然之前有很多类似的问题被问过,但我没有找到合适的答案:(。例如Similar question

我的DataGridView.Cellvalues 以编程方式根据数据绑定源进行更改。我想跟踪某些列的总和,但 DataGridView.CellValueChanged 事件仅在单元格具有焦点时适用(不是以编程方式更改的情况)。由于性能原因,我不想使用 RowPrePaint Event 或 CellPainting events。

有什么合适的活动或方法吗?

【问题讨论】:

  • 你试过DataSourceChanged事件吗?
  • 是的,我试过 DataSourceChanged 事件没有引发:(
  • 它肯定会在适当的条件下被提升,但我们无法猜测您的确切条件是什么。请发布代码的相关部分,描述“以编程方式按数据绑定源”的含义。
  • @varocarbas 这里是示例代码BindingList<ClassA> Items = new BindingList<ClassA>();DataGridView1.DataSource=SomeObject.Items;
  • 首先,你应该编辑你的问题而不是写评论,这样每个人都可以立即了解整个情况。其次,这段代码没有太多意义。你为什么不保持简单,只是为了了解出了什么问题?一个可以肯定工作的代码:DataTable dt = new DataTable(); dt.Columns.Add("Col 1"); dt.Rows.Add("1"); dt.Rows.Add("2"); dataGridView1.DataSource = dt; 您不必总是依赖DataTable 来设置DataGridViewDataSource,但它是最简单/始终有效的选项,肯定会触发上述事件.

标签: c# winforms data-binding datagridview


【解决方案1】:

我遇到了类似的问题,并使用 DataBindingComplete 事件解决了它。

对于仅处理某些列,这对您来说应该会很好,因为我相信它只在数据绑定操作完成后调用一次。

您需要根据需要在网格中进行自己的迭代,因为 DataGridViewBindingCompleteEventArgs 显然没有 RowIndex 和 ColumnIndex 属性,但您可以执行以下操作:

private void DataGridView1_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
{
    var senderGrid = (DataGridView)sender;

    foreach (DataGridViewRow row in senderGrid.Rows)
    {
        // Determine the bound data object for the current row
        var currentRowObj = row.DataBoundItem;

        // Access the data in a particular cell on this row
        var cellToTotal = row.Cells["Column1"];

        etc
    }
}

【讨论】:

    猜你喜欢
    • 2023-03-16
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    • 2014-09-15
    • 2019-03-14
    • 2016-01-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多