问题
I have a Windows form which is taking forever to load data into my datagridview.
I keep getting the error in this line:
dataGridView1.Rows.Add(row);
Cross-thread operation not valid: Control 'dataGridView1' accessed from a thread other than the thread it was created on.
Here is my code:
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();
}
}
}
Please show me where I am going wrong
Thanks
回答1:
Your "getBarcodProperty" function is being called from another thread and not from UI thread and you are try to access datagridview in that method so it created problem.
There are two ways two solve problem.
- In your load method "RFID_Load(object sender, EventArgs e)" add this line as first line. ( In this case you don't have to change any of your code)
Control.CheckForIllegalCrossThreadCalls = false;
More detail : http://dotnetstep.blogspot.in/2009/09/cross-thread-operation-not-valid.html
- Another solution is to use delegate.
dataGridView1.Invoke(new Action(() => { dataGridView1.Rows.Add(row); }));
Note: For each call you have to do same thing.
回答2:
Try this:
dataGridView1.Invoke(new Action(() => dataGrideView1.Rows.Add(row)));
But in case of wpf you have to use dispatcher: Change WPF controls from a non-main thread using Dispatcher.Invoke;
来源:https://stackoverflow.com/questions/38932898/cross-thread-operation-not-valid-control-datagridview1-accessed-from-a-thread