2011-10-04 66 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'屬性更改一切工作正常。 –

相關問題