c# - 编辑单元格后重新绑定 DataGridView 的问题
问题描述
我有一个DataGridView
,它是自定义控件的一部分。这个自定义控件的界面公开了一个属性,该属性只接受一个DataTable
可以设置为DataSource
DataGridView 的属性。
当用户编辑其中一个单元格的内容时,我想在最后一列中设置一个特殊值,说明该行已被修改。
我从 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();
}
}
推荐阅读
- xamarin - 如何使用两帧的绝对布局?
- java - 如何在 Java 11 上使用 Web 服务?包 javax.jws 不存在
- javascript - 在坐标系中查找大多数未填充的点
- ruby-on-rails - 在 rails start 上找不到此 localhost 页面
- c# - 在邮件正文中创建表结构的html标签设计应该是什么
- python - CherryPy AttributeError: 'Module_six_moves_urllib_parse' 对象没有属性 'unquote _to_bytes'
- google-apps-script - Google 应用程序脚本:autoResizeColumn 工作不正确,无法按预期工作
- javascript - 如何从ejs模板调用外部文件的javascript函数?
- javascript - 用新数据重新加载 ngx-graph
- soap - 使用 Apache Camel 在肥皂消息中添加标题块