Assuming you have a reference to your form as form1, and that form has a label named label1 that is public/accessible to TestClass:
public class TestClass
{
public void myLoop()
{
for (int i = 1; i <= 1000; i++)
{
// show value of i to label
form1.label1.Text = i.ToString();
// allow message pumping to redraw the label
Application.DoEvents();
// pause long enough to see it before the next one happens
System.Threading.Thread.Sleep(100);
}
}
}
I wouldn't recommend using Application.DoEvents for production code normally; but if you are running the UI thread and not using async code, this would be the "hacky" way to get all the window events pumping (mostly WM_PAINT to get the label to redraw itself) during your loop.
A better way is to use events:
public class TestClass {
public class ProgressEventArgs : EventArgs {
public int Value { get; set; }
}
public event EventHandler<ProgressEventArgs> Progress;
public void myLoop() {
for (int i = 0; i <= 1000; ++i) {
var evt = Progress;
if (evt != null) {
evt.Invoke(this, new ProgressEventArgs() { Value = i; });
}
}
}
}
and handle that event in the form:
public class TestForm : Form {
private somevent_click(object sender, EventArgs evt) {
var test = new TestClass();
test.Progress += test_Progress;
test.myLoop();
}
private void test_Progress(object sender, TestClass.ProgressEventArgs evt) {
label1.Text = evt.Value;
}
}
Note that these will happen in the same thread, so depending on what else you do in your loop, you may not get message pumping. Consider using a background thread or async code instead.