码迷,mamicode.com
首页 > 编程语言 > 详细

多线程中操作UI

时间:2017-12-14 23:49:36      阅读:255      评论:0      收藏:0      [点我收藏+]

标签:代码   hang   span   状态   row   ui控件   pre   datagrid   stat   

遇到过要在工作线程中去更新UI以让用户知道进度,而在多线程中直接调用UI控件操作是错误的做法。

最后解决方法是将操作UI的代码封装,通过Invoke / BeginInvoke 去委托调用。

代码封装好的方法例子如下:

        private void UpdatelblText(string str)
        {
            if (lblText.InvokeRequired)
            {
                lblText.Invoke(new Action<string>(UpdatelblText), str);
            }
            else
            {
                lblText.Text = str;
            }
        }

另外一个例子:

        private void ChangeColor(int row, string ShowColor, string InvoiceStatus, string PrintStatus)
        {
            if (dataGridView1.InvokeRequired)
            {
                this.Invoke(new Action<int, string, string, string>(ChangeColor), new object[] { row, ShowColor, InvoiceStatus, PrintStatus });
            }
            else
            {
                if (ShowColor == "Green")
                {
                    dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.Green;
                    dataGridView1.Rows[row].DefaultCellStyle.ForeColor = Color.White;
                }
                else if (ShowColor == "Yellow")
                {
                    dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.Yellow;
                    dataGridView1.Rows[row].DefaultCellStyle.ForeColor = Color.Black;
                }
                else if (ShowColor == "Red")
                {
                    dataGridView1.Rows[row].DefaultCellStyle.BackColor = Color.Red;
                    dataGridView1.Rows[row].DefaultCellStyle.ForeColor = Color.White;
                }
                dataGridView1.Rows[row].Cells[2].Value = InvoiceStatus;//开票状态
                dataGridView1.Rows[row].Cells[3].Value = PrintStatus;//打印状态
            }

        }

 

直接调用:

UpdatelblText("正在组织数据...");

 

多线程中操作UI

标签:代码   hang   span   状态   row   ui控件   pre   datagrid   stat   

原文地址:http://www.cnblogs.com/qiuguochao/p/8040494.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!