i have the following code that updates my progress bar in visual c sharp. it works fine and the bar moves for each percentage. but i also have code that i got from a post on another site, that is suppose to put the progress bar value in the middle of the progress bar as % percentage. it displays the % of the progress bar value for a split second but then disappears. i am new to c sharp and have tried several things like pBar.update and pBar.refresh after the pBar value change. i have edited some of the code to make it easier to understand. see below, once i reportprogress the background worker progresschanged executes and again the pBar value changes i see it change, and also the textbox text gets updated, but for some reason the code further below that draws the % text within the progress bar gets overwritten somehow. again i see the % for a split second. you can see some of my comments where i was trying various things to see if it would redraw the %
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
backgroundWorker1.ReportProgress(10);
collect_long_process();
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
pBar.Value = e.ProgressPercentage;
txtBox_pBar.Text = "Gathering info";
int percent = 10;//(int)(((double)pBar.Value / (double)pBar.Maximum) * 100);
pBar.CreateGraphics().DrawString(percent.ToString() + "%", new Font("Arial", (float)8.25, FontStyle.Regular),
Brushes.Black, new PointF(pBar.Width / 2 - 10, pBar.Height / 2 - 7));
//pBar.Update();
//Application.DoEvents();
}
That code is wrong.
You need to handle the progress bar’s
Paintevent and draw one.Graphics.Otherwise, your drawing will be overwritten next time the control paints itself.
In general, you should never draw on
CreateGraphics().