我有一个用 .net-4.0 编写的 C# Windows 窗体应用程序
我有一个数据 GridView (dgvItems
),我在导入函数的末尾以编程方式将其绑定(bind)到数据集和数据表。
我有一个导入按钮,可以将数据从选定的 excel 文件导入到名为 _dtItemAdjustList
的表格中,一旦数据被导入,我就将该表格绑定(bind)到我的网格。我用来绑定(bind)网格的代码是:
dgvItems.DataSource = _dsQtyAdjust;
dgvItems.DataMember = "Item Adjust List";
dgvItems.Refresh();
到目前为止一切正常,如果我在 datagridview 中编辑导入的数据,它会在编辑每个单元格后更新绑定(bind)表 _dtItemAdjustList
。
当我尝试手动向我的 datagridview 添加一行时,我的问题出现了,它不会立即将该新行添加到绑定(bind)的数据表。
示例:我在 dgvItems_CellValueChanged
事件的末尾放置了一个断点,并添加了一个 _dtItemAdjustList.Rows.Count
watch ,结果如下。
数据导入后,我编辑了一个现有的导入行, watch 显示正确的行数,比方说 5。
现在我点击最后一个 * 行,在我的 item# 列中输入一些内容并点击选项卡,断点触发但我的行数仍然只显示 5,我又填写了几个单元格在新行中,但每次我离开一个单元格时,我的 CellValueChanged 事件都会触发,并且行数保持在 5。
接下来,我添加了第二个手动行,现在,在我从第一个单元格中跳出并填写第二个新行后,我的行计数器立即变为 6,但从技术上讲,此时我已将 2 手动行添加到我导入的 5,因此计数器应显示为 7
这会重复,基本上每个新的手动添加到 datagridview 的行都不会添加到绑定(bind)的数据表中,直到 a) 添加另一行或 b) 我去返回并重新编辑现有行上的单元格。
编辑 忘了说我试过用两种方式绑定(bind)我的 DataGridView:
DataSource = _dsQtyAdjust //dataset Name
DataMember = "Item Adjust List" // Table Name in the dataset
DataSource = _dtItemAdjustList
就我的新行行为而言,这没有任何区别。
最佳答案
好的,经过大量的反复试验和在线搜索,我找到了一个似乎可行的解决方案。
我没有将我的 DataGridView 直接绑定(bind)到我的 DataTable,而是创建了一个 BindingSource,将 BindingSource 绑定(bind)到我的 DataTable,然后将我的 DataGridView 绑定(bind)到 BindingSource,最后在我的 dgvItems_CellValueChanged
事件中我使用了以下组合EndEdit()
和 NotifyCurrentCellDirty(true/false)
使其工作。
代码示例:
public partial class frmQuantityAdjustment : Form
{
// In my forms partial class I created a new public BindingSource
public BindingSource bsItemAdjust = new BindingSource();
}
private void frmQuantityAdjustment_Load(object sender, EventArgs e)
{
// In my form_Load event I bound the BindingSource to my DataTable
// and then the DataGridView to the BindingSource
bsItemAdjust.DataSource = _dtItemAdjustList;
dgvItems.DataSource = bsItemAdjust;
dgvItems.Refresh();
}
private void dgvItems_CellValueChanged(object sender, DataGridViewCellEventArgs e)
{
// Finally at the end of my CellValueChanged event I added the
// following code
bsItemAdjust.EndEdit();
dgvItems.NotifyCurrentCellDirty(true);
dgvItems.EndEdit();
dgvItems.NotifyCurrentCellDirty(false);
}
我在 this thread 上遇到了这个解决方案经过一些测试后,它似乎运行良好。
现在,我的 DataGridView 中的新行已添加到 CellValueChanged 事件结束时绑定(bind)的 DataTable。
关于winforms - 手动向 DataGridView 添加新行不会立即更新绑定(bind)的 DataTable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31195979/