Update a textbox ???

B

Billy Bob

Hello

I'm wanting to run through a for loop, and update a text box control to the
value as I loop through, but the only value thats's ever displayed in the
text box is that last value of the counter. Am I missing something???

As I step into the code, I can see the textbox1 test gets update, but I
never see it in the actual text box

private void button1_Click(object sender, EventArgs e)

{

for (int y = 1; y <= 5000; y++)

{

int x = Thread.CurrentThread.GetHashCode();

textBox1.Text = "The number is" + y.ToString();

Thread.Sleep(2000);

}

}
 
S

senfo

Billy said:
Hello

I'm wanting to run through a for loop, and update a text box control to the
value as I loop through, but the only value thats's ever displayed in the
text box is that last value of the counter. Am I missing something???

As I step into the code, I can see the textbox1 test gets update, but I
never see it in the actual text box

private void button1_Click(object sender, EventArgs e)

{

for (int y = 1; y <= 5000; y++)

{

int x = Thread.CurrentThread.GetHashCode();

textBox1.Text = "The number is" + y.ToString();

Thread.Sleep(2000);

}

}

That's because you're making the main thread sleep, which means the UI
will not repaint. This isn't ever a good idea. To accomplish your
desired affect, you'll have to run that code in a second thread. Just
don't forget to check the value of InvokeRequired if you hope to update
the UI thread from your second thread.

http://msdn2.microsoft.com/en-us/library/system.windows.forms.control.invokerequired.aspx

Hope that helps,
 
S

Stoitcho Goutsev \(100\)

It is not even that. The problem is that during the loop the UI thread
doesn't process messages from the message queue because the UI thread is
busy running the loop. If the messages are not processed no painting will be
perfomed. The easiest fix would be to put inside the loop after seting the
Text property the following line of code:

Appliation.DoEvents();
 
B

Billy Bob

Thanks for the tip, that works for me.

Stoitcho Goutsev (100) said:
It is not even that. The problem is that during the loop the UI thread
doesn't process messages from the message queue because the UI thread is
busy running the loop. If the messages are not processed no painting will
be perfomed. The easiest fix would be to put inside the loop after seting
the Text property the following line of code:

Appliation.DoEvents();
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top