ASP.net:在多线程里查询数据库并填充dataGrid

出处:http://9host.cn/asp.net/2007417222322.htmlhtml

 

ASP.net:在多线程里查询数据库并填充dataGrid

 

 

在查询大数据量时,窗体界面会不动,“正在查询...”的提示也不能显示。因此打算用多线程来实现,但是当在线程里面执行到 this.dataGridDF.DataSource=dt.DefaultView;填充数据时却提示报错,说什么该线程不能调用主线程建立的控件等等。web

  后来查了许多资料,终于搞定。能够在查询数据库时操做别的了,“正在查询...”的提示也显示了。数据库

  //或者在前面用一个线程查询,在线程里调用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; 
相关文章
相关标签/搜索