3

例子:

此时在我的代码中,进度条为 70:

pbUpload.Value = 70;

foreach (string file in finalFiles)
{
    //processes
    //processes
}

finalFiles 具有可变长度。这意味着它没有固定的数字。所以基本上我需要先弄清楚数字,这很容易,但是我如何构建一个循环,它将进度条从 70 更新到 100(100 是最后一个“每个”元素)?

4

2 回答 2

5

这更简单:

int count = finalFiles.Length;
int current = 0;
foreach (string file in finalFiles)
{
    current++;
    pbUpload.Value = current / count * 30 + 70;
}

祝你好运!

于 2012-08-16T19:43:45.953 回答
2

用于BackgroundWorker此。

public partial class Form1 : Form
{
   public Form1()
   {
       InitializeComponent();
       Shown += new EventHandler(Form1_Shown); 
       backgroundWorker1.WorkerReportsProgress = true;
       backgroundWorker1.DoWork += new DoWorkEventHandler(backgroundWorker1_DoWork);
       backgroundWorker1.ProgressChanged += 
       new ProgressChangedEventHandler(backgroundWorker1_ProgressChanged);
       pbUpload.Value = 70;
   }

   void Form1_Shown(object sender, EventArgs e)
   {
       backgroundWorker1.RunWorkerAsync();
   }

   int val = 0;

   void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
   {
       val = (100 - pbUpload.Value) / finalFiles.Length;

       foreach (string file in finalFiles)
       {
           //Your processes
           backgroundWorker1.ReportProgress(pbUpload.Value + val);
       }
   }  

   void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
   {
        pbUpload.Value = e.ProgressPercentage;
   }
}
于 2012-08-16T19:33:26.947 回答