如何根据基于变量数组运行的foreach循环更新进度条?

时间:2012-08-16 19:32:18

标签: c# foreach progress-bar

示例:

在我的代码中,进度条位于70:

pbUpload.Value = 70;

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

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

2 个答案:

答案 0 :(得分:4)

这更简单:

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

答案 1 :(得分:1)

请使用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;
   }
}