You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

DataGridView在DataTable复制回写后丢失数据源的问题

为什么DataGridView在重新赋值DataTable后丢失数据源?

这个问题我碰到过好多次了,本质是对象引用的问题,咱们一步步理清楚:

问题出在哪?

当你第一次执行 dataGridView1.DataSource = dt; 时,DataGridView绑定的是你最初创建的那个dt对象实例。后来你做了这两步:

dt1 = dt.Copy();
dt.Clear();

这时候原来的dt实例被清空了,但DataGridView还是绑定着它。接下来你执行 dt = dt1.Copy(); —— 这其实是把dt变量指向了一个全新的DataTable对象,而DataGridView并没有和这个新对象建立绑定关系,它还盯着那个已经被清空的旧dt实例,所以网格自然就没数据了。

怎么解决?

给你三种实用的解决方案,按需选择:

方案1:直接重新绑定数据源

最简单粗暴的办法,赋值新的dt后,重新把它设置给DataGridView:

dt = dt1.Copy();
dataGridView1.DataSource = dt; // 关键:告诉网格用新的DataTable

方案2:复用原来的DataTable实例(避免重新绑定)

如果不想重新设置DataSource,可以保留原来的dt实例,把dt1的数据导入进去,这样绑定关系不会断:

// 先清空原dt的现有行
dt.Clear();
// 把dt1的每一行导入到原dt中
foreach (DataRow row in dt1.Rows)
{
    dt.ImportRow(row);
}
// 这时候网格会自动刷新,因为绑定的还是原来的dt实例,数据更新后会同步

方案3:用BindingSource做中间层(更优雅的长期方案)

推荐用BindingSource作为DataGridView和DataTable之间的代理,这样后续替换DataTable时,只需要修改BindingSource的数据源,不用动DataGridView:

// 初始化时就引入BindingSource
BindingSource bindingSource = new BindingSource();

// 给dt加数据后,把dt绑定到BindingSource
dt.Columns.Add("id", typeof(int));
dt.Columns.Add("name", typeof(string));
dt.Rows.Add(1, "One");
dt.Rows.Add(2, "Two");
dt.Rows.Add(3, "Three");
bindingSource.DataSource = dt;

// 把BindingSource设置为DataGridView的数据源
dataGridView1.DataSource = bindingSource;

// 后续复制和恢复操作
dt1 = dt.Copy();
dt.Clear();

// 恢复数据时,直接更新BindingSource的数据源即可
bindingSource.DataSource = dt1.Copy(); // 如果不需要新副本,直接用bindingSource.DataSource = dt1;

内容的提问来源于stack exchange,提问作者Azoz Azozz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:16:12