Label Text in FOR Loop

Hello Everyone,

Thank you for stopping by and assisting. I'm trying to print numbers in a label but I'm not having success. For example, I have the following code:
1
2
3
4
5
6
7
8
9
	private: System::Void txtLeftWheel_Click_1(System::Object^  sender, System::EventArgs^  e) 
	{
		for (int i = 1; i <= 1000; i++)
		{
			Sleep(100);
			this->lblLeftWheel->Text = (Int32::Parse(this->lblLeftWheel->Text) + i).ToString();
			
		}
	}

The idea is that when I click the button, the numbers on the label increment from 1 to 1000. The Sleep() is there to slow down the loop and the user can see something happening. However, if I put the Sleep() before the label->, the form freezes completely. If I put the Sleep() after the label-> text, the form freezes for a few seconds and the label text goes from 1 and jumps straight to 1000.

The expected functionality is that the label displays numbers 1 through 1000 but increment every second.

I appreciate all your help!
You should move this to the windows programming section you will get more help probably.

Though I don't see why you would have different results with sleep before or after changing the text if they are both inside the for loop.
My guess is that probably the window needs to poll events and draw its data for the user to see anything, and if you are just sleeping without doing anything then the window will simply pause a while and then go back. Probably a better idea is to keep a counter and a timer, so each cycle you check the timer to see if 100ms has passed. If it has, you go into the function, increment the counter and set the label to that value, resetting the timer in the process. Once the counter hits 1000, then simply set some kind of flag to prevent the function being called again and reset the counter to 0.
Topic archived. No new replies allowed.