ASP.net:在多線程裏查詢數據庫並填充dataGrid

出處:http://9host.cn/asp.net/2007417222322.html

 

ASP.net:在多線程裏查詢數據庫並填充dataGrid

 

 

在查詢大數據量時,窗體界面會不動,“正在查詢...”的提示也不能顯示。所以打算用多線程來實現,可是當在線程裏面執行到 this.dataGridDF.DataSource=dt.DefaultView;填充數據時卻提示報錯,說什麼該線程不能調用主線程創建的控件等等。

  後來查了許多資料,終於搞定。可以在查詢數據庫時操作別的了,“正在查詢...”的提示也顯示了。

  //或者在前面用一個線程查詢,在線程裏調用dataGrid.BeginInvoke(異步方法)來單獨填充
 
 
  1. public delegate void myDelegate(); 
  2. DataTable dt; 
  3.  
  4. private void btnDianJia_Click(object sender, System.EventArgs e) 
  5.  try 
  6.  { 
  7.   mythread = new Thread(new ThreadStart(ThreadWork)); 
  8.   mythread.Start();     
  9.  } 
  10.  catch(System.Exception ex) 
  11.  { 
  12.   MessageBox.Show(this,ex.Message,"提示",MessageBoxButtons.OK,MessageBoxIcon.Information); 
  13.  }    
  14.  
  15. void ThreadWork() 
  16.  this.dataGridDJ.CaptionText="正在查詢電價數據..."
  17.  mf.statusBarPanel1.Text="正在查詢電價數據..."
  18.  this.Cursor=Cursors.WaitCursor; 
  19.  
  20.  
  21.  string shijian=this.dateTimeDianJia.DateValue; 
  22.  DateTime today=DateTime.Today; 
  23.  string mingcheng=this.txtMingCheng.Text; 
  24.  string leibie=this.cmbBoxLiebie_DJ.SelectedValue.ToString(); 
  25.  PowerWeb.BLL.DianFeiDianJia.DianJia dj=new PowerWeb.BLL.DianFeiDianJia.DianJia(); 
  26.  
  27.  if(shijian==today.ToString("yyyyMM")) 
  28.  { 
  29.   dt=dj.GetList(leibie,mingcheng).Tables[0]; 
  30.  } 
  31.  else 
  32.  { 
  33.   dt=dj.GetListOld(leibie,mingcheng,shijian).Tables[0]; 
  34.  } 
  35.  this.dataGridDJ.CaptionText=shijian+"電價信息 (共計條"+dt.Rows.Count.ToString()+"記錄)"
  36.  
  37.  dataGridDJ.BeginInvoke(new myDelegate(FillData));//異步調用(來填充) 
  38.   
  39.  this.Cursor=Cursors.Default; 
  40.  mf.statusBarPanel1.Text="查詢結束"
  41.  
  42. private void FillData() 
  43.  this.dataGridDJ.DataSource=dt.DefaultView; 

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章