blah blah blah is here! blah blah » Close

up1down
link

hi,

Could I have some C# code example of how to use the progress bar, with the percentage of completion? For example, during execution of some code, says in Counting Down from 1000 to Zero, I would like to send the progress bar moving with the percentage of completion inside.
also, how are we to change the color of the progress bar? for example, if the status is a success, I would like the progress bar to be green, but if it is a failure, I would like the progress bar to be red color.

thanks.

last answered one year ago

11 answers

link

The BackgroundWorker is really good for this. In fact, it was - at least partially - designed for it! :)

public partial class Form1 : Form
{
private BackgroundWorker worker;

public Form1()
{
InitializeComponent();
progressBar1.Minimum = 0;
progressBar1.Maximum = 100;
}

private void Form1_Load(object sender, EventArgs e)
{
worker = new BackgroundWorker();
worker.DoWork += new DoWorkEventHandler(worker_DoWork);
worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
worker.WorkerReportsProgress = true;
progressBar1.Value = progressBar1.Minimum;
worker.RunWorkerAsync();
}

void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
label1.Text = e.ProgressPercentage + "%";
}

void worker_DoWork(object sender, DoWorkEventArgs e)
{
for (int i = 1000; i >= 0; i--)
{
Thread.Sleep(50);
int percent = (1000 - i) / 10;
worker.ReportProgress(percent);
}
}
}


As for changing the color of the bar, I don't know if you can do that - but post it here if you find a way :)

gsvirdi
412

BINGO !!!!!!!!!!! . . . . . . . . . . . . Wonderful help, this was a wonderful code :)

yonifra
18

Great explanation! Thanks man!

up1down
link

you can find ur answer in this thread by making a thread or a background worker:
http://www.debugging.com/bug/23453

considering changing the progress bar color, you have to use the user32.dll code to change the color of a window control or can change the forecolor while enablingvisualstyle. You can find it in this page:

http://stackoverflow.com/questions/778678/how-to-change-the-color-of-progressbar-in-c-net-3-5

up2down
link

On the color changing point, according to the documentation you can't change the foreground and background colors in XP and above if you've enabled visual styles. However, these are enabled by default when you create a windows forms application in VS.

If you examine the Main() method in your program.cs file, you'll need to remove this line to disable them:

Application.EnableVisualStyles();

However, if you do so then the application may not look as good as it did before :(

If that's the case, then I'd look for a custom ProgessBar control which does allow you to change colors (there's sure to be one on Code Project) or sub-class the standard one and paint the bar yourself.

gsvirdi
412

I agree with vulpes, the application will REALLY not look gud after disabling system visual styles. Like always vulpes have a solution + observation to offer. :)

up0down
link

That is a wonderful code from Foamy. Thank You very much.

I want the percentage to be inside the Progress Bar, so I have this: But the percentage disappears after it reaches 100%. How do I enable the percentage to be visible even after it reaches 100%? thanks.

void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;

int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
progressBar1.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));

// label1.Text = e.ProgressPercentage + "%";
}

up0down
link

As I didn't knew how to bring that % count embidded into the progressBar1 so I had customised it with a solution from my fresher's head:

progressBar1 > Right Click > send to back,
label1 > Right Click > bring to front,
Dragged label1 in middle of progessBar1

then I added the code

if (percent==100)
{
label1.Text = "Loading Complete";
}


If I had to answer ur question then what I would do is "Trick the output" :
// in label1's property I would put label1's text as ="";

// Then in worker_ProgressChanged I will put
if (percent==100)
{
label1.Text=e.ProgressPercentage+"%";
or
label1.Text = "100%";
}


I know this is not the correct way, but I'm still learning u know. :)

up0down
link

I think the problem is that you're not erasing the previous percentage before drawing the new one and consequently you're getting a jumble of the two.

Whilst gsvirdi's suggestion works, the bar is obscured by the label.

Try this instead:

// add this private field
private int lastPercentage = 0;

void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
if (e.ProgressPercentage == lastPercentage) return; //EDIT added this line
progressBar1.Value = e.ProgressPercentage;
Graphics g = progressBar1.CreateGraphics();
Font f = new Font("Arial", 8.25f, FontStyle.Regular);
int w = progressBar1.Width / 2 - 10;
int h = progressBar1.Height / 2 - 7;
SolidBrush sb = new SolidBrush(progressBar1.BackColor);
g.DrawString(lastPercentage.ToString() + "%", f, sb, w, h);
g.DrawString(e.ProgressPercentage.ToString() + "%", f, Brushes.Black, w, h);
sb.Dispose();
f.Dispose();
g.Dispose();
lastPercentage = e.ProgressPercentage;
}

up0down
link

hi Vulpes,

my code below works, but the last 100% disappears. Yours 100% disappear too. I want the 100% to be visible.

void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;

int percent = (int)(((double)progressBar1.Value / (double)progressBar1.Maximum) * 100);
progressBar1.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular), Brushes.Black, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));

}

vulpes
17279

All I can say is that both your code and mine worked fine when I tested them, displaying the final 100%.The only difference is that I couldn't read the 100% using your code as it was overlaying the 99% displayed earlier. Incidentally, I'm using the algorithm in foamy's code example to generate the percentages. Are you sure that whatever algorithm you're using actually generates 100% before the task completes? Does gsvirdi's approach display 100%?

up0down
link

foamy's and gsvirdi's code works fine with the Label, able to display the final 100%, but the bar is obscured by the label, which I do not want. I want the percentage to be inside the progress bar, without using the label.

your code and my code is not able to display the final 100%, persistently on the progress bar.

vulpes
17279

So, how quickly does it disappear and are you doing anything in particular when it does so or is the application just idling? If foamy's reading this, it may be time for another sanity check on yours truly :)

up0down
link

Will it be acceptable for u to keep the label1 on right side (end) of the progressBar1? This way till 99% the percentage is shown inside the progress bar, but on 100% the label1 on the end of the progress bar will show the progress percentage. I'm sorry as I won't be able to help with the code, I still have a long path to become expert in codeing :)

up0down
link

if it is some complex functions that takes some time to complete, and I want to trace its progress in percentage, how do I do that? I notice that the count down loop is easy to trace its percentage, because it has a variable counter. but say those complex functions call some other functions, how do I trace its progress till completion?

thanks.

up0down
link

It depends on the circumstances.

Sometimes there's no practicable way to measure progress towards completion, using a simple mathematical formula.

In such cases, you need to estimate in advance how long the operation will take and then change the ProgressBar in accordance with the percentage time elapsed since inception. You also need to avoid moving the progress bar up to 100% until the overall task has completed.

To give a smoother result, you might also want to set intermediate 'wait points' which are not to be exceeded until a particular sub-task has been completed and then to recalculate the estimated time to completion at those points.

Feedback