我在从另一个线程更新 DataGridView
时遇到问题。让我解释。当用户单击表单上的按钮时,我需要用一些行填充网格。这个过程需要一些时间,所以我在一个单独的线程中进行。在启动线程之前,我将 DataGridView.Enabled
属性设置为 false
,以防止用户在添加项目时编辑项目,并且在工作线程结束之前我设置了 >Enabled
返回到 true
。
问题是如果需要显示滚动条,DataGridView
将无法正确更新其内容。我将用截图来说明这一点:
如您所见,最后一个可见行被部分绘制,DataGridView
不会向下滚动。如果我调整网格大小,使其重新绘制自身,所有行都会正常显示。
这是一些代码:
private void button1_Click(object sender, EventArgs e)
{
string[] fileNames = new string[] { "file1", "file2", "file3" };
Thread AddFilesToListThread = new Thread(ThreadProcAddRowsToGrid);
dataGridView1.Enabled = false;
AddFilesToListThread.Start(fileNames);
}
delegate void EmptyDelegate();
private void ThreadProcAddRowsToGrid(object fileNames)
{
string[] files = (string[])fileNames;
foreach (string file in files)
{
EmptyDelegate func = delegate
{
dataGridView1.Rows.Add(file);
};
this.Invoke(func);
}
EmptyDelegate func1 = delegate
{
dataGridView1.Enabled = true;
};
this.BeginInvoke(func1);
}
我还注意到只有 Enabled
属性会导致这种奇怪的行为。例如,更改 BackgroundColor
效果很好。
能帮我看看问题出在哪里吗?
最佳答案
你试过DataGridView.Refresh()
也许设置只读属性而不是 dataGridView1.Enabled = true;?
或者,我认为这可以通过将数据与 UI 分离来解决。
在我看来,这是 SO 的一个简化示例,但如果可以的话,我建议替换等效行;
dataGridView1.Rows.Add(file);
与
DataTable table = getData(); //In your snippet (file)
BindingSource source = new BindingSource();
source.DataSource = table
dataGridView1.Datasource = source;
然后您还可以使用 BindingSource 上的 ResetBindings 刷新数据;
table = getData();; //Update your data object
source.ResetBindings(false);
关于c# - 从另一个线程更新时,DataGridView 不会重新绘制自身,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7646491/