2010-12-04 66 views
0

我已經寫了這段代碼從Excel文件讀取數以千計的行並將它們加載到DataGridView中。BackgroundWorker問題

但是我面臨的問題是,無論加載哪個文件,DataGridView都只顯示第一個文件的行,並且_list從不清除。

public class MyForm : Form 
{ 
    private List<Student> _list = null; 

    private void LoadFile_Click(object sender, EventArgs e) 
    { 
     try 
     { 
      if (_list != null) 
      { 
       _list.Clear(); 
      } 

      openFileDialog1.ShowDialog(); 

      _connStr = MakeConnectionString.GetConnectionString(openFileDialog1.FileName); 

      if (!string.IsNullOrEmpty(_connStr)) 
      { 
       backgroundWorker1.RunWorkerAsync(); 
      } 
     } 
     catch 
     { 
      MessageBox.Show("Application is busy with the first task!", "Busy...", MessageBoxButtons.OK, MessageBoxIcon.Warning); 
     } 
    } 

    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
    { 
     if (backgroundWorker1.CancellationPending) 
     { 
      e.Cancel = true; 
      return; 
     } 

     IDataReader read = StudentDA.GetReader(_connStr); 
     List<Student> localList = null; 

     if (_list != null) 
     { 
      _list.Clear(); 
     } 
     _list = StudentMapper.GetStudents(read); 


     localList = new List<Student>(_list); 

     dataGridView1.Invoke(new MethodInvoker(delegate 
     { 
      dataGridView1.Rows.Clear(); 
     })); 

     foreach (Student std in localList) 
     { 
      dataGridView1.Invoke(new MethodInvoker(delegate 
      { 
       dataGridView1.Rows.Add(std.SerialNo, std.RollNo); 
      })); 
     } 
    } 
} 
+0

您是否清除列表並不重要,因爲a:您不是數據綁定的,b:您在下一行重新分配列表;我仍然看... – 2010-12-04 12:17:06

+0

清除您的_list運行工人完成事件處理程序 – TalentTuner 2010-12-04 12:20:52

回答

1

嘗試在每次加載新數據時創建一個新的BackgroundWorker對象。

你是不是chaning的_connection對象

static _connection = null; 

if(_connection == null) 
    { 

    } 

這隻會工作,當你改變了這個連接沒有得到改變的文件適用於第1次和下一次。

1

你確定沒有發生異常嗎?嘗試處理完成事件,並檢查暴露在event-arg對象上的異常

另外;每個步驟中有一個單一調用的循環可能會減慢速度;也許在後臺執行數據提取,然後在單個Invoke中執行整個清除/添加循環。如果那太多了,至少要把它分成幾組;或考慮虛擬模式(這對於大數據量來說效率更高)。

相關問題