我正在尝试使用ProgressBar
将BackgroundWorker
数据集的进度转换为Excel。问题是这项工作是在与ProgressBar
不同的班级完成的,我在循环中调用worker.ReportProgress(...)
时遇到了困难。我很抱歉,如果这是一件容易的事情,但我是C#的新手并且一整天都在尝试这一点而且似乎无法做到这一点。非常感谢您的帮助。
namespace CLT
{
public partial class GenBulkReceipts : UserControl
{
private void btnOpen_Click(object sender, EventArgs e)
{
Cursor.Current = Cursors.WaitCursor;
try
{
OpenFile();
}
Cursor.Current = Cursors.Default;
}
private void OpenFile()
{
if (dsEx1.Tables[0].Rows.Count > 0)
{
backgroundWorker1.RunWorkerAsync(dsEx1);
}
}
public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
DataSet ImportDataSet = e.Argument as DataSet;
AccountsToBeImported = new BLLService().Get_AccountsToBeReceipted(ImportDataSet);
}
public void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
this.progressBar1.Value = e.ProgressPercentage;
}
// ...
}
}
namespace BLL
{
class GenBulkReceiptsBLL
{
public DataSet Get_AccountsToBeReceipted(DataSet dsImport)
{
DataSet dsReturn = AccountsDAL.QGenReceiptAccounts(0,0,"");//Kry Skoon DataSet wat ge-populate moet word
CLT.GenBulkReceipts pb = new CLT.GenBulkReceipts();
int TotalRows = dsImport.Tables[0].Rows.Count;
//pb.LoadProgressBar(TotalRows);
int calc = 1;
int ProgressPercentage;
foreach (DataRow dr in dsImport.Tables[0].Rows)
{
ProgressPercentage = (calc / TotalRows) * 100;
//This is the problem as I need to let my Progressbar progress here but I am not sure how
//pb.worker.ReportProgress(ProgressPercentage);
}
return dsReturn;
}
// ...
}
}
答案 0 :(得分:1)
您需要将worker
传递给Get_AccountsToBeReceipted
方法 - 然后才能调用BackgroundWorker.ReportProgress
:
// In GenBulkReceipts
public void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
BackgroundWorker worker = sender as BackgroundWorker;
DataSet importDataSet = e.Argument as DataSet;
AccountsToBeImported =
new BLLService().Get_AccountsToBeReceipted(importDataSet, worker);
}
// In GenBulkReceiptsBLL
public DataSet Get_AccountsToBeReceipted(DataSet dsImport,
BackgroundWorker worker)
{
...
worker.ReportProgress(...);
}
或者,您可以让GenBulkReceiptsBLL
拥有自己的Progress
事件,并从GenBulkReceipts
订阅 - 但这会更复杂。
答案 1 :(得分:0)
您的班级GenBulkReceiptsBLL
需要对BackgroundWorker
个实例进行一些引用。您可以通过各种方式实现这一目标。其中一个建议就是在实例化时将引用传递给类。
例如,由于GenBulkReceipts
是实例化GenBulkReceiptsBLL
的类,因此在GenBulkReceiptsBLL
的构造函数中,您可以传递当前正在BackgroundWorker
的实例在GenBulkReceipts
中使用。这样您就可以直接拨打ReportProcess(...)
。或者,您可以将引用直接传递给Get_AccountsToBeReceipted(...)
方法。