I'm trying to show progress bar as much as the amount of records marked in the checkbox column. But I couldn't.

C#
if (dataGridView1.Rows.Count > 100)
{
int total = 500; /
for (int i = 0; i <= total; i++)
{
System.Threading.Thread.Sleep(100);
int percents = (i * 100) / total;
backgroundWorker1.ReportProgress(percents, i);
}
}
else if (dataGridView1.Rows.Count < 100)
{
int total = 100;
for (int i = 0; i <= total; i++)
{
System.Threading.Thread.Sleep(50);
int percents = (i * 100) / total;
backgroundWorker1.ReportProgress(percents, i);
}
}
Tahir AnsariRank #366 · 6.8K reputationPosted Aug 11, 2023, 10:08 AM EDT
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { int totalRecords = dataGridView1.Rows.Count; int totalIterations = totalRecords > 100 ? 500 : 100; for (int i = 0; i 100 ? 100 : 50); int percents = (i * 100) / totalIterations; backgroundWorker1.ReportProgress(percents, i); } } private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar1.Value = e.ProgressPercentage; labelProgress.Text = $"Progress: {e.ProgressPercentage}%"; // Use e.UserState to get the current iteration if needed int currentIteration = (int)e.UserState; // You can update your DataGridView here based on the currentIteration } private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) { // Handle completion or any cleanup here }DoWorkevent handler of theBackgroundWorker.ProgressChangedevent is used to update the progress bar and any UI elements you need to update.RunWorkerCompletedevent is used to handle any post-work cleanup or tasks.Tahir AnsariRank #366 · 6.8K reputationPosted Aug 11, 2023, 11:53 AM EDT
Modify
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) { int totalRecords = dataGridView1.Rows.Count; for (int i = 0; i < totalRecords; i++) { // Save the current data record here int percents = (i * 100) / totalRecords; backgroundWorker1.ReportProgress(percents, i); System.Threading.Thread.Sleep(50); // Adjust sleep duration as needed } }Mehmet FatihRank #1,474 · 1.1K reputationPosted Aug 11, 2023, 11:21 AM EDT
Thank you Tahir. Your code is working fine but when I save 50 datas or even only one data, the progress bar is runsing at the same speed. What is the reason of this?
Tahir AnsariRank #366 · 6.8K reputationPosted Aug 11, 2023, 11:51 AM EDT
due to the fact that your progress update logic is based on a fixed number of iterations (
totalIterations) rather than being tied directly to the number of records being processed.Mehmet FatihRank #1,474 · 1.1K reputationPosted Aug 11, 2023, 12:16 PM EDT
When I tried the second codes, I saves the unchecked lnes too. I had tried a similiar code to the second before.
Mehmet FatihRank #1,474 · 1.1K reputationPosted Aug 11, 2023, 12:56 PM EDT
What is the solution then?