2010-12-04 2 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

リストをクリアするかどうかは、データバインディングではなく、b:次の行にリストを再割り当てするかどうかに関係ありません。私はまだ見ています... –

+0

作業者が完了したイベントハンドラで_listをクリアします – TalentTuner

答えて

1

新しいBackgroundWorkerオブジェクトを作成するたびに、新しいデータを読み込みます。

あなたはこれが唯一の第一の時間とあなたは、この接続が変更になっていないファイルを変更する次の時間のために働く動作します_connectionオブジェクトに

static _connection = null; 

if(_connection == null) 
    { 

    } 

をchaningされていません。

+0

コードを投稿できますか? – TalentTuner

+0

backgroundworkerを使ってコードを実行して動作するかどうかを確認しますか? – TalentTuner

+0

私はあなたの問題を持っています..待って、これが問題であるかどうかを見てください – TalentTuner

1

どこかで例外が発生していないことは確実ですか?完了イベントを処理し、event-argオブジェクトに公開されている例外を確認してください。

また、各ステップで1つのInvokeを持つループがおそらく遅くなるでしょう。おそらく、データ復帰をバックラウンドで行い、その後、単一のInvokeでclear/add-loop全体を実行します。それが多すぎる場合は、少なくともそれを小さなセットにまとめてください。仮想モードを検討することができます(これは、大容量のデータボリュームではるかに効率的です)。

関連する問題