C#& SQL:如何更新表而不刷新DataGridView? [英] C# & SQL : how to update table without refreshing DataGridView?
问题描述
我一直使用
DataGridView.DataSource = (DataTable)tbl;
但是这种方法完全刷新了Datagridview,像是selectedrows,scrollbar position,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);
更新:上面的方法是最简单的,评论,它有副作用,由于合并
方法优化,在操作过程中抑制更改通知,并提高 ListChanged
事件最后使用 ListChangedType.Reset
。所以,这是一个简单而有效的方法,根据 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!