我总是用
DataGridView.DataSource = (DataTable)tbl;
但是这种方法完全刷新了 Datagridview,比如 selectedrows、滚动条位置、backColor 等.我只想从 SQL 更新单元格数据,而没有完整的 datagridview 刷新
But this method is completely refresing the Datagridview something like selectedrows, scrollbar position, backColor etc.. I only want to update cell data from SQL witouth full datagridview refresh
例如 uTorrent 有一个类似 datagridview 的表格,在某些单元格中 x KB/s 的值总是在刷新,但 torrentdatagrid 是静态的.没有滚动移动,没有选择消失等.
For Example uTorrent has a table like datagridview, and in some cells x KB/s values always refresing but torrentdatagrid is static. there is No scroll moving, no selection dissapearing etc.
你能帮我做这件事吗?
对不起,我的英语不好.谢谢.
I'm sorry for my bad English. Thanks.
如果你的表有一个主键,并且你只想更新现有的/添加新的行,你可以使用 DataTable.Merge 方法 像这样:
If your table has a primary key, and you want only to update existing/add new rows, you can use DataTable.Merge Method like this:
最初
dataGridView.DataSource = initial_data_table;
更新
((DataTable)dataGridView.DataSource).Merge(new_data_table);
更新: 上面的方法是最简单的,但正如评论中提到的,由于 Merge
方法优化会在操作并以 ListChangedType.Reset
最后引发 ListChanged
事件.所以,这是一个简单而有效的方法,它基于 DataTable.LoadDataRow 方法:
UPDATE: The method above is the simplest, but as mentioned in the comments, it has side effects due to the Merge
method optimizations which suppress the change notifications during the operation and raising ListChanged
event with ListChangedType.Reset
at the end. So, here is a simple and effective method that does the trick, based on DataTable.LoadDataRow Method:
foreach (var dataRow in newTable.AsEnumerable())
table.LoadDataRow(dataRow.ItemArray, LoadOption.OverwriteChanges);
还有一个样本证明:
using System;
using System.Data;
using System.Linq;
using System.Windows.Forms;
namespace Samples
{
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
var form = new Form();
var dg = new DataGridView { Dock = DockStyle.Fill, Parent = form };
var data = GetData();
dg.DataSource = data;
var updateTimer = new Timer { Interval = 200, Enabled = true };
updateTimer.Tick += (sender, e) =>
{
foreach (var dr in GetData().AsEnumerable())
data.LoadDataRow(dr.ItemArray, LoadOption.OverwriteChanges);
};
Application.Run(form);
}
static DataTable GetData()
{
var dt = new DataTable();
dt.Columns.Add("Id", typeof(int));
dt.Columns.Add("Name");
dt.Columns.Add("Score", typeof(int));
dt.PrimaryKey = new[] { dt.Columns["Id"] };
var random = new Random();
for (int i = 1; i <= 1000; i++)
dt.Rows.Add(i, "Player #" + i, random.Next(1, 100000));
return dt;
}
}
}
这篇关于C# &SQL:如何在不刷新 DataGridView 的情况下更新表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!