c# - 从另一个线程更新时,DataGridView 不会重新绘制自身

标签 c# winforms multithreading datagridview

我在从另一个线程更新 DataGridView 时遇到问题。让我解释。当用户单击表单上的按钮时,我需要用一些行填充网格。这个过程需要一些时间,所以我在一个单独的线程中进行。在启动线程之前,我将 DataGridView.Enabled 属性设置为 false,以防止用户在添加项目时编辑项目,并且在工作线程结束之前我设置了 >Enabled 返回到 true

问题是如果需要显示滚动条,DataGridView 将无法正确更新其内容。我将用截图来说明这一点:

partially drawn row

如您所见,最后一个可见行被部分绘制,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/

相关文章:

C# : Show dialog on UI thread from another thread

c - 使用信号量在 Sleeping Barber 中打印

c# - WCF 服务应用程序 - 使用 C++ 对象调用导致 Visual Basic 6.0 DLL 文件挂起

c# - 使用数据集 [asp.net, c#] 在 SQL Server 中添加新行

c# - 在 RichTextBox 中突出显示花费的时间太长

c# - 如何避免在 C# 中进行类型检查以加载正确的 UI?

java - java中的中断线程

c# - WinForm 应用程序数据持久性 (C#)

c# - 删除所有 DataGrid 行和单元格边框

c# - 更改 WinForms 控件的边框颜色和外观