C# Label Text Not Updating

…衆ロ難τιáo~ 提交于 2019-12-18 19:08:59

问题


I have the following code:

private void button1_Click(object sender, EventArgs e)
{
  var answer =
    MessageBox.Show(
      "Do you wish to submit checked items to the ACH bank? \r\n\r\nOnly the items that are checked and have the status 'Entered' will be submitted.",
      "Submit",
      MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question,
      MessageBoxDefaultButton.Button1);

  if (answer != DialogResult.Yes)
    return;

  button1.Enabled = false;
  progressBar1.Maximum = dataGridView1.Rows.Count;
  progressBar1.Minimum = 0;
  progressBar1.Value = 0;
  progressBar1.Step = 1;

  foreach (DataGridViewRow row in dataGridView1.Rows)
  {
    if ((string) row.Cells["Status"].Value == "Entered")
    {
      progressBar1.PerformStep();

      label_Message.Text = @"Sending " + row.Cells["Name"].Value + @" for $" + row.Cells["CheckAmount"].Value + @" to the bank.";
      Thread.Sleep(2000);
    }
  }
  label_Message.Text = @"Complete.";
  button1.Enabled = true;
}

This is a test I am creating to port over to my application. Everything works fine but the label_Message.text being set. It never shows up on the screen. It is being set, I did a console.write on it to verify. It's just not refreshing the screen. I get the "Complete" at the end also.

Anyone have any ideas?


回答1:


You're performing a lengthy operation on the UI thread. You should move it to a background thread (via BackgroundWorker for instance) so the UI thread can do things like repaint the screen when needed. You can cheat and execute Application.DoEvents, but I'd really recommend against it.

This question and answer are basically what you're asking:
Form Not Responding when any other operation performed in C#




回答2:


use Label.Refresh(); it saves a lot of time.This should work for u




回答3:


The Label doesn't re-paint until you give the UI thread back to the message loop. Try Label.Refresh, or better yet, try putting your lengthy operation in a background thread as other posters have suggested.




回答4:


This operation is executed in UI thread. UI won't update until it's finished. To make it update during sending you must perform sending in separate thread and update the label from there




回答5:


This usually happens when you're doing intensive calculations/iterations in the same thread as where the user interface elements are running. To work around this you're going to need to have a separate thread do the work and from there update the label's value accordingly. I'd post a complete source sample but I'm away from my dev machine at the moment.



来源:https://stackoverflow.com/questions/5680659/c-sharp-label-text-not-updating

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!