我有一个Windows表单,它将永远将数据加载到我的datagridview中.
我一直在这行中得到错误:
dataGridView1.Rows.Add(row);
Run Code Online (Sandbox Code Playgroud)
跨线程操作无效:控制'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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
请告诉我我哪里出错了
谢谢
dot*_*tep 10
你的"getBarcodProperty"函数是从另一个线程而不是从UI线程调用的,你试图在该方法中访问datagridview,因此它产生了问题.
两种解决问题的方法有两种.
Control.CheckForIllegalCrossThreadCalls = false;
更多细节:http://dotnetstep.blogspot.in/2009/09/cross-thread-operation-not-valid.html
dataGridView1.Invoke(new Action(()=> {dataGridView1.Rows.Add(row);}));
注意:对于每次通话,您必须做同样的事情.
小智 7
尝试这个:
dataGridView1.Invoke(new Action(() => dataGrideView1.Rows.Add(row)));
Run Code Online (Sandbox Code Playgroud)
但是在 wpf 的情况下,您必须使用调度程序:使用 Dispatcher.Invoke 从非主线程更改 WPF 控件;
| 归档时间: |
|
| 查看次数: |
10307 次 |
| 最近记录: |