【发布时间】:2014-03-27 01:56:05
【问题描述】:
我正在尝试在用户完成单元格编辑后更新数据库中的值。由于 DataBinding 此特定数据集涉及一些复杂性,因此需要手动(和动态)填充 DataGridView。
在CellEndEdit 的事件处理程序中,我调用了我的方法将值更新回数据库,它按计划工作。当我尝试重新填充 DataGridView 时出现问题。供参考,此方法称为PopulateAccounts()。
在单元格中输入值后,如果用户按键盘上的 Enter 或单击表单上的另一个控件,则一切正常。但是,单击同一 DataGridView 中的另一个单元格会导致以下错误:
操作无效,因为它会导致对 SetCurrentCellAddressCore 函数的可重入调用。
PopulateAccounts() 方法包括引发错误的DataGridView.Rows.Clear()。我在一些相关的 SO 问题中研究了这个错误,它似乎与线程有关,我对此一无所知。一种建议的解决方法是调用我的 PopulateAccounts() 方法:
BeginInvoke(new MethodInvoker(PopulateAccounts));
这可行,但它会导致 DataGridView 选择已编辑单元格之前的所有单元格(见下面的屏幕截图)
同样,这仅发生在点击离开单元格并进入另一个单元格时。否则,即按 Enter 或单击另一个控件,它只会选择第一个单元格。
这里是 PopulateAccounts() 的代码供参考:
// Populates the DataGridView's account records.
private void PopulateAccounts()
{
dgvShed.Rows.Clear();
using (PassShedEntities context = new PassShedEntities(conString))
{
foreach (Account acct in context.Account.Where(a => a.Category_id == (int)lstCategories.SelectedValue))
{
dgvShed.Rows.Add();
foreach (DataGridViewColumn col in dgvShed.Columns)
{
Credential cred = (from c in context.Credential
join f in context.Field on c.Field_id equals f.Id
join a in context.Account on c.Account_id equals a.Id
where c.Account_id == acct.Id
where f.Label == col.Name
select c).SingleOrDefault();
dgvShed.Rows[dgvShed.Rows.Count - 1].Cells[col.Name].Tag = cred.Id;
dgvShed.Rows[dgvShed.Rows.Count - 1].Cells[col.Name].Value = cred.Value;
}
}
}
}
【问题讨论】:
-
您可以在帖子中添加 PopulateAccounts 代码吗?
-
完成。 dgvShed.Rows.Clear() 方法抛出错误。
标签: c# winforms datagridview