C# 编辑单元格后重新绑定DataGridView时出现问题
我有一个C# 编辑单元格后重新绑定DataGridView时出现问题,c#,.net,winforms,datagridview,C#,.net,Winforms,Datagridview,我有一个DataGridView,它是自定义控件的一部分。此自定义控件的接口公开了一个属性,该属性仅接受可设置为DataGridView的数据源的DataTable 当用户编辑其中一个单元格的内容时,我想在最后一列中设置一个特殊值,说明行已被修改 我从DataGridView的CellEndEdit事件的自定义控件中公开一个公共事件。在使用此控件的表单中,我使用以下事件处理程序订阅此事件: private void myCustomControl_CellEndEdit(object sende
DataGridView
,它是自定义控件的一部分。此自定义控件的接口公开了一个属性,该属性仅接受可设置为DataGridView的数据源的DataTable
当用户编辑其中一个单元格的内容时,我想在最后一列中设置一个特殊值,说明行已被修改
我从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();
}
这将引发以下异常:
如上面的代码片段所示,我尝试挂起绑定以解决此问题,但没有效果。可能是什么问题?我不知道您的代码是如何工作的,但我认为在DataGridView中使用BindingSource作为数据源可能是问题的解决方案
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();
}
}
此外,我还质疑为什么要“复制”数据源?这似乎没有必要。我认为错误应该在以下行上…temp.Rows[rowIndex][colIndex]=“Modified”代码>…但是,由于这是数据源的“副本”,因此它可能会在数据源更改时向下延伸。您是否尝试过“不”复制原始数据源,因为它看起来完全不必要?@JohnG我也开始这么想。我将尝试直接修改数据源。