我有以下代码:
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;
}
我正在创建此测试以移植到我的应用程序。一切正常,但设置了label_Message.text。它永远不会显示在屏幕上。正在设置它,我在上面做了console.write来验证。只是不刷新屏幕。最后我也得到了“完成”。
谁有想法?
最佳答案
您正在对UI线程执行冗长的操作。您应该将其移至后台线程(例如,通过BackgroundWorker
),以便UI线程可以在需要时执行诸如重新绘制屏幕的操作。您可以作弊并执行Application.DoEvents
,但是我真的建议您反对它。
这个问题和答案基本上就是您要问的:
Form Not Responding when any other operation performed in C#
关于c# - C#标签文字未更新,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5680659/