2011-10-04 65 views
3

从另一个线程更新DataGridView时出现问题。让我解释。当用户单击表单上的按钮时,我需要用一些行填充网格。这个过程需要一些时间,所以我在一个单独的线程中完成。在开始线程之前,我将DataGridView.Enabled属性设置为false,以防止用户在添加项目时编辑项目,并在工作线程结束之前将其设置为Enabled回到true当从另一个线程更新时,DataGridView不会重新绘制自己

问题是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工作正常。

你能帮我看看问题出在哪里吗?

回答

2

你试过DataGridView.Refresh()

也许设置只读属性,而不是dataGridView1.Enabled = TRUE;?

另外,我认为这可能是通过从用户界面分离您的数据解决。

在我看来,这是一个简化的例子,在这里,但如果你可以,我会建议更换等值线;

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); 
+0

是的,我尝试在启用网格后放置一个'Refresh()',但它不会帮助。 –

+0

更新可能的替代方案,我雇用似乎帮助我 – Coops

+0

我还没有尝试过,但我想指出,没有'Enabled'属性更改一切工作正常。 –

相关问题