Click here to Skip to main content
15,886,026 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
I want in this code in the any step label show the Number of that step.
In the my code just show last number in the label!

I also Label.Invalidate() the done, but do not work.

private void button1_Click(object sender, EventArgs e)
   {
       int i = 0;
       while (i<100)
       {
           i++;
           label1.Text = string.Format("Step is :{0}", i);
           System.Threading.Thread.Sleep(1000);
       }
   }
Posted
Updated 2-Feb-11 14:38pm
v4

Your Label is unable to display the step numbers either because your steps complete so quickly that it the last number is the only one on screen long enough to register, or, more likely, because the main thread, which also deals with displaying the GUI, is so busy doing your steps that it has no time to display the numbers.

I'll let you guess which is happening.

Here[^] is an article that does roughly what you need. See if you can adapt the code in it for your application.
 
Share this answer
 
I already gave a comprehensive answer to another question, see

Changes step by step to show a control[^].

You can use BackgroundWorker class.

What you're trying to do is a big sin: 1) your are blocking UI thread with you sleep, 2) you're assigning property in the loop, but in can not be processed because you are blocking event processing of the main UI loop; DoEvent is a big no-no (as a rule of thumb).

—SA
 
Share this answer
 
v2
There are better ways, but here is the simple way that will show you the basics:
C#
private void button1_Click(object sender, EventArgs e)
{
    var t = new System.Threading.Thread(new System.Threading.ThreadStart(() =>
    {
        int i = 0;
        while (i < 10)
        {
            i++;
            var ts = new System.Threading.ThreadStart(() =>
            {
                label1.Text = string.Format("Step is: {0}", i.ToString());
            });
            if (this.InvokeRequired)
                this.Invoke(ts);
            else
                ts();
            System.Threading.Thread.Sleep(1000);
        }
    }));
    t.Start();
}

Basically, you run your code on a different thread than the main thread. This frees the main thread to perform UI updates. Whenever you need to change the UI, you must invoke your code on the main thread.
 
Share this answer
 
Comments
fjdiewornncalwe 2-Feb-11 20:38pm    
+5. It's refreshing to see someone else use this syntax to kick off a small, functional child thread.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900