首页 > 解决方案 > 编辑单元格后重新绑定 DataGridView 的问题

问题描述

我有一个DataGridView,它是自定义控件的一部分。这个自定义控件的界面公开了一个属性,该属性只接受一个DataTable可以设置为DataSourceDataGridView 的属性。

当用户编辑其中一个单元格的内容时,我想在最后一列中设置一个特殊值,说明该行已被修改。

我从 DataGridView 事件的自定义控件公开了一个公共CellEndEdit事件。在使用此控件的表单中,我使用以下事件处理程序订阅此事件:

private void myCustomControl_CellEndEdit(object sender, EventArgs e)
{
    // plan of attack:
    // - copy the DataTable into a new temporary one
    // - modify the appropriate column in the affected row
    // - bind the new table to the control

    // get the row and column indexes of the modified cell
    int rowIndex = ((DataGridViewCellEventArgs)e).RowIndex;
    int colIndex = ((DataGridViewCellEventArgs)e).ColumnIndex;
   
    DataTable temp = this.dataTable.dataSource.Copy();
    temp.Rows[rowIndex][colIndex] = "Modified";

    // bind the modified table
    CurrencyManager cm = (CurrencyManager)BindingContext[dataTable.dataSource];
    cm.SuspendBinding();
    myCustomControl.dataSource = temp; // this is the offending line
    cm.ResumeBinding();        
}

这会引发以下异常:

在此处输入图像描述

如上面的代码片段所示,我曾尝试暂停绑定以解决此问题,但无济于事。可能是什么问题?

标签: c#.netwinformsdatagridview

解决方案


我不知道您的代码是如何工作的,但我认为在您的DataGridView中使用BindingSource作为DataSource可能是您问题的解决方案。

public class MyDataGridView : Form
{
  private BindingSource bindingDataSource = new BindingSource();
  private DataTable myDataTable; 

  public MyDataGridView()
  {
      InitializeComponent();
     
      //Set Data Source to DataTable
      bindingDataSource.DataSource = myDataTable; 

      //Use BindingSource as DataSource
      this.dataGridView.DataSource = bindingDataSource;
  }
  
  //...

  private void myCustomControl_CellEndEdit(object sender, EventArgs e)
  {
     //Update your datatable values 
     this.myDataTable.Rows[colIndex].Value = "Modified";

     //Refresh your grid data binding
     this.bindingDataSource.ResetBindings(metadataChanged: false);
     this.dataGridView.Refresh();
  }
}

推荐阅读