如何解决编辑单元格后重新绑定DataGridView遇到麻烦
我有一个DataGridView
,它是自定义控件的一部分。此自定义控件的界面公开了仅包含DataTable
的属性,可以将其设置为DataGridView的DataSource
。
当用户编辑其中一个单元格的内容时,我想在最后一列中设置一个特殊值,表明该行已被修改。
我从自定义控件公开了一个用于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 作为 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();
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。