【问题标题】:Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on [duplicate]跨线程操作无效:控件“dataGridView1”从其创建的线程以外的线程访问[重复]
【发布时间】:2016-12-20 08:23:08
【问题描述】:

我有一个 Windows 表单,它需要永远将数据加载到我的 datagridview 中。

我不断收到这一行的错误:

    dataGridView1.Rows.Add(row);

跨线程操作无效:控件“dataGridView1”从创建它的线程以外的线程访问。

这是我的代码:

    public List<string> _checked = new List<string>();

    private void getBarcodProperty()
    {                
        string query = "select Name from RfidUnic where Barcode = @barcode";

        while (true)
        {
            while (_checked.Count > 0)
            {
                SQLiteCommand cmd = new SQLiteCommand(query, sqliteConnection);
                cmd.Parameters.AddWithValue("@barcode", _checked[0]);
                sqliteConnection.Open();

                SQLiteDataReader da = cmd.ExecuteReader();

                if (da.Read())
                {
                    if (!da.IsDBNull(0))
                    {
                        string[] row = new string[] { da[0].ToString(), "1", _checked[0] };
                        dataGridView1.Rows.Add(row);
                        _checked.RemoveAt(0);
                    }
                }
                else
                {
                    string[] row = new string[] { "empty", "1", _checked[0] };
                    dataGridView1.Rows.Add(row);
                    _checked.RemoveAt(0);
                }

                sqliteConnection.Close();
            }
        }
    }

请告诉我哪里出错了

谢谢

【问题讨论】:

    标签: c# multithreading


    【解决方案1】:

    您的“getBarcodProperty”函数是从另一个线程而不是从 UI 线程调用的,您尝试在该方法中访问 datagridview,所以它产生了问题。

    两种解决问题的方法。

    1. 在您的加载方法“RFID_Load(object sender, EventArgs e)”中,将此行添加为第一行。 (在这种情况下,您不必更改任何代码)

    Control.CheckForIllegalCrossThreadCalls = false;

    更多详情:http://dotnetstep.blogspot.in/2009/09/cross-thread-operation-not-valid.html

    1. 另一种解决方案是使用委托。

    dataGridView1.Invoke(new Action(() => { dataGridView1.Rows.Add(行); }));

    注意:对于每个呼叫,您必须做同样的事情。

    【讨论】:

    【解决方案2】:

    试试这个:

    dataGridView1.Invoke(new Action(() => dataGrideView1.Rows.Add(row)));
    

    但在 wpf 的情况下,您必须使用调度程序:Change WPF controls from a non-main thread using Dispatcher.Invoke;

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-01-15
      • 2016-05-21
      • 2016-06-11
      • 2015-05-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多