Reputation: 17
I am adding string values to the listbox from List<>. I want to calculate Progress Percentage in ReportProgress method.please help me to calculate progress percentage. I have written 0 in first parameter of ReportProgress method. I want to replace that 0 with progress percentage.
Here is my code.
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
List<string> result = new List<string>();
var found = obj.getFiles();
foreach (var item in found)
{
if (item.Contains("SFTP:") || item.Contains("ERROR:"))
{
result.Add(item);
(sender as BackgroundWorker).ReportProgress(0, item);
}
else
(sender as BackgroundWorker).ReportProgress(0);
System.Threading.Thread.Sleep(1000);
}
e.Result = result;
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.UserState != null)
listBox1.Items.Add(e.UserState);
progressBar2.Value = e.ProgressPercentage;
}
Upvotes: 0
Views: 1333
Reputation: 1416
Foreach is not necessarily the best iteration for this application. Use a for-loop and use the index to calculate the progress based on the size of found.
for (int i = 0; i < found.Count; i++)
{
int progress = (int)(((float)(i + 1) / found.Count) * 100);
if (found[i].Contains("SFTP:") || found[i].Contains("ERROR:"))
{
result.Add(found[i]);
(sender as BackgroundWorker).ReportProgress(progress, found[i]);
}
else
(sender as BackgroundWorker).ReportProgress(progress);
System.Threading.Thread.Sleep(1000);
}
Upvotes: 1