[英]C# - Datagridview update
我的应用程序需要使用数据库中的数据定期自动更新datagridview,以反映系统中的更改,这不是问题。
我的问题是,在更新datagridview时,它会短暂冻结UI并阻止滚动。 因此,我可以想到两种可能的解决方案:
在UI事件处于活动状态时暂停更新-尽管我不知道什么是全局用户事件?
还是使用后台工作程序更新datagridview-尽管我不知道您将如何从后台工作程序更新UI?
using (SqlDataAdapter a = new SqlDataAdapter("SELECT Name,Value FROM dbo.IOData", c))
{
DataTable IOProcData = new DataTable();
// Populate data table
a.Fill(IOProcData);
// Record displayed row
int temp = dataGridView1.FirstDisplayedScrollingRowIndex;
IOBinding.DataSource = IOProcData;
// Reset displayed row
if (temp > 0)
{
dataGridView1.FirstDisplayedScrollingRowIndex = temp;
}
}
编辑:
是否有一个事件会在首次单击datagridview的滚动条(例如mousedown而不是滚动条)时触发? 滚动事件在滚动动作之后发生,所以会迟到。
您可以分离职责。 您的耗时过程可能是从数据库获取数据,而不是分配数据源。
在您的backgroundWorker中,您可以从数据库中获取信息。 完成后,只需将填充的表分配给您的gridview。
这是一个例子:
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {
if (e.Error != null) {
//Handle error
} else {
IOBinding.DataSource = (DataTable)e.Result;
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {
using (SqlDataAdapter a = new SqlDataAdapter("SELECT Name,Value FROM dbo.IOData", c)) {
DataTable IOProcData = new DataTable();
// Populate data table
a.Fill(IOProcData);
// Record displayed row
e.Result = a;
}
}
您可以初始化一个Timer线程,该线程负责获取新数据并更新您的DataGrid。
internal void InitTimer()
{
_timer = new Timer();
_timer.Tick += (sender, args) => BindDataGrid();
_timer.Interval = 1000;
_timer.Start();
_timerStart = true;
}
关于滚动问题,在更新selectedRow变为0之前,我遇到了另一个问题。我通过将DataTable绑定到DataGrid并将两个结果合并在一起解决了这个问题。
var newData = // your data as DataTable Format;
// Get Current Scroll position
var scrollingRowIndex = MyDataGridView.FirstDisplayedScrollingRowIndex;
// Get Current Row
var currentRow = MyDataGridView.CurrentCell != null
? MyDataGridView.CurrentCell.RowIndex
: -1;
DataTable bindedData;
var currentDataSource = MyDataGridView.DataSource as DataTable;
if (currentDataSource != null)
{
currentDataSource.Merge(newData);
bindedData = currentDataSource;
}
else
{
bindedData = newData;
}
MyDataGridView.DataSource = bindedData;
MyDataGridView.Update();
// set Current Scroll position
if (scrollingRowIndex > -1)
MyDataGridView.FirstDisplayedScrollingRowIndex = scrollingRowIndex;
// set Current Row
if (currentRow > -1)
MyDataGridView.Rows[currentRow].Selected = true;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.