【发布时间】:2011-09-01 20:57:30
【问题描述】:
我想遍历在 BackgroundWorker 的主窗体上创建的 DataGridView,以将数据导出到 CSV 文件。 BackgroundWorker 是在单独的表单上创建的,导出进度将通过进度条显示。这是调用BackgroundWorker的导出表单上的代码:
private DataGridView exportGrid;
public void ExportCSV(DataGridView mainGrid)
{
this.exportGrid = mainGrid;
//Set progress bar maximum
progressBar1.Maximum = mainGrid.Rows.Count;
if (backgroundWorker1.IsBusy != true)
{
//Start the asynchronous operation
backgroundWorker1.RunWorkerAsync();
}
//Show the form
this.ShowDialog();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
//Write data rows
foreach (DataGridViewRow row in exportGrid.Rows)
{
//Check if the background worker has been cancelled
if (worker.CancellationPending == true)
{
e.Cancel = true;
break;
}
else
{
foreach (DataGridViewCell cell in row.Cells)
{
if (cell.Visible)
{
//Do CSV writing here...
}
}
//Report current progress to update UI
worker.ReportProgress(row.Index + 1);
}
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
//Update progress bar
this.progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
//Close the form once the background worker is complete
this.Close();
}
此代码导致以下错误:
- BindingSource 不能是它自己的数据源。不要设置 DataSource 和 DataMember 属性指向返回的值 绑定源。
- 跨线程操作无效:从 线程不是创建它的线程。
我认为这是因为我在未创建 DataGridView 的线程中访问它。这样做的最佳方法是什么?有没有可能?
更新:
我循环通过 DataGridView 而不是数据源的原因是用户将更改列顺序、排序顺序和显示/隐藏网格的列,他们希望这些更改反映在导出的数据中。有没有其他方法来处理这个问题?
【问题讨论】:
-
这个 DataGridView 的行数有多大?
-
目前它有超过 80,000 行。
标签: c# winforms multithreading