2009-09-22 55 views
0

如何使用線程更改Gridview中的某些單元格?我有一個來自數據庫的查詢,它用了很多時間來查詢。所以它非常慢,我想使用線程更快加載數據。此外,線程完成後,它的工作可以更改網格視圖中的數據?如何使用線程更改Gridview中的某些單元格?

+0

問題是如何實現線程或如何在填充網格時避免跨線程異常? – DaveShaw 2011-02-05 23:30:51

+0

請更具體。你有什麼不明白? – 2011-02-05 23:43:25

回答

0
using System.Threading; 
using System.Threading.Tasks; 

public partial class Form1 : Form 
{ 
    public Form1() 
    { 
     InitializeComponent(); 
     dataGridView1.DataSource = new List<Test>() { new Test { Name = "Original Value" } }; 
    } 

    // Start the a new Task to avoid blocking the UI Thread 
    private void button1_Click(object sender, EventArgs e) 
    { 
     Task.Factory.StartNew(this.UpdateGridView); 
    } 
    // Blocks the UI 
    private void button2_Click(object sender, EventArgs e) 
    { 
     UpdateGridView(); 
    } 

    private void UpdateGridView() 
    { 
     //Simulate long running operation 
     Thread.Sleep(3000); 
     Action del =() => 
      { 
       dataGridView1.Rows[0].Cells[0].Value = "Updated value"; 
      }; 
     // If the caller is on a different thread than the one the control was created on 
     // http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invokerequired%28v=vs.110%29.aspx 
     if (dataGridView1.InvokeRequired) 
     { 
      dataGridView1.Invoke(del); 
     } 
     else 
     { 
      del(); 
     } 
    } 
} 
相關問題