text on progressbar in c#

jack rasha picture jack rasha · Nov 24, 2011 · Viewed 17.2k times · Source

I am using the following code.

Why does it not run properly ?

private void Form1_Shown(object sender, EventArgs e)
{
    for (int i = 1; i <= 100; i++)
    {
        Application.DoEvents();
        Thread.Sleep(200);

        progressBar1.Refresh();
        progressBar1.Value = i;
        progressBar1.CreateGraphics().DrawString(i.ToString() + "%",
            new Font("Arial", (float)8.25, FontStyle.Regular),
            Brushes.Black, new PointF(progressBar1.Width / 2 - 10,
                progressBar1.Height / 2 - 7));


    }
}

update :

Why does not always show the text ?

Answer

Alex picture Alex · Nov 24, 2011

This works - although I'd set the thread-sleep to more than 200 ms. Your problem was that you did the work in the UI thread and this way it never gets updated. For better visibility, just change the font color:

 private void Form1_Load(object sender, EventArgs e)
{
  Task t = new Task(() => StartUpdate());
  t.Start();

  t.ContinueWith(task => Console.WriteLine("Done loading"));
}

 private void StartUpdate()
{
  for (int i = 1; i <= 100; i++)
  {
    UpdateProgressBar(i);
  }
}

private void UpdateProgressBar(int i)
{
  if (progressBar1.InvokeRequired)
  {
    progressBar1.Invoke(new Action<int>(UpdateProgressBar), new Object[] { i });
  }
  else
  {
    Thread.Sleep(200);
    progressBar1.Refresh();
    progressBar1.Value = i;
    progressBar1.CreateGraphics().DrawString(i.ToString() + "%", new Font("Arial",
                                          (float)10.25, FontStyle.Bold),
                                          Brushes.Red, new PointF(progressBar1.Width / 2 - 10, progressBar1.Height / 2 - 7));
  }
}