我已經寫了這段代碼從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);
}));
}
}
}
您是否清除列表並不重要,因爲a:您不是數據綁定的,b:您在下一行重新分配列表;我仍然看... – 2010-12-04 12:17:06
清除您的_list運行工人完成事件處理程序 – TalentTuner 2010-12-04 12:20:52