我有一个 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();
}
}
}
请告诉我哪里出错了
Thanks
您的“getBarcodProperty”函数是从另一个线程而不是从UI线程调用的,并且您尝试在该方法中访问datagridview,因此它产生了问题。
有两种方法可以解决问题。
- 在您的加载方法“RFID_Load(object sender, EventArgs e)”中添加此行作为第一行。 (在这种情况下,您不必更改任何代码)
Control.CheckForIllegalCrossThreadCalls = false;
更多详情 :http://dotnetstep.blogspot.in/2009/09/cross-thread-operation-not-valid.html http://dotnetstep.blogspot.in/2009/09/cross-thread-operation-not-valid.html
- 另一种解决方案是使用委托。
dataGridView1.Invoke(new Action(() =>
{
dataGridView1.Rows.Add(行);
}));
注意:对于每个调用,您都必须执行相同的操作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)