将行添加到DataGridView后程序停止,为什么?

时间:2014-03-20 20:12:10

标签: c# winforms datagridview

我的数据网格视图有问题,在我添加一行后程序冻结,这是我的代码:

private void ActivityLogAddRow(bool status, string desc, AVType avt)
    {
            DataGridViewRow row = new DataGridViewRow();
            DataGridViewCell imageCell = new DataGridViewImageCell();
            if (status == true)
                imageCell.Value = Properties.Resources.success;
            else
                imageCell.Value = Properties.Resources.failure;
            DataGridViewCell timeCell = new DataGridViewTextBoxCell();
            timeCell.Value = DateTime.Now;
            DataGridViewCell typeCell = new DataGridViewTextBoxCell();
            typeCell.Value = avt.ToString();
            DataGridViewCell descCell = new DataGridViewTextBoxCell();
            descCell.Value = desc;
            row.Cells.Add(imageCell);
            row.Cells.Add(timeCell);
            row.Cells.Add(typeCell);
            row.Cells.Add(descCell);
            dataGridView1.Rows.Add(row);
        }

我可以看到添加到数据网格视图中的行而不是它(程序)停止,任何正文都有线索?

p.s添加行需要一点点时间(比如几秒钟)

更新

我得到两个线程访问Datagridview的异常,我该如何解决?互斥?

2 个答案:

答案 0 :(得分:0)

如果您尝试更改将行添加到以下内容的方式,该怎么办:

 DataTable table = new DataTable();
    table.Columns.Add("Img",typeof(System.Drawing.Image));
    table.Columns.Add("Time");
    table.Columns.Add("Type");
    table.Columns.Add("Desc");
    DataRow dr = table.NewRow();
    if (status == true)
           dr["Img"]  = Properties.Resources.success;
        else
           dr["Img"]  = Properties.Resources.failure;
    dr["Time"] = DateTime.Now;
    dr["Type"] = avt.ToString();
    dr["Desc"] = desc;
    table.Rows.Add(dr);

datagridview1.DataSource = table;

答案 1 :(得分:0)

Windows中的任何UI控件都遵循STA线程模型。单线程公寓。任何控件都由创建它的线程拥有,并且只允许此线程更新它。这可以追溯到ActiveX时代 - 并且因为任何Windows UI控件必须与ActiveX兼容(否则标准文件对话框之类的东西将无效)它就位。它还使得任何UI工作变得更加容易,因为您可以确保在执行UI操作时,没有其他线程会更新UI - 很好并且同步。

这就是为什么C#应用程序中的主线程默认标记为STAThread。有关详细信息,请访问Why do all Winforms programs require the [STAThread] attribute?

因此,您的后台线程不允许直接进行更改。

但是,您可以使用INVOKE方法在UI线程中执行代码块。

为此我建议你阅读

http://www.codeproject.com/Articles/2083/The-key-to-multi-threaded-Windows-Forms-UI-interac

解释了如何操作 - 或者使用文档并阅读UI控件/窗口上的Invoke方法。调用Invoke会在UI线程中执行包含代码块,然后可以更新UI。

所以,背景工作者 - >获取数据 - >调用UI来更新数据。

相关问题