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
Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on. BUT BUT BUT... it seems I'm back to square one. The Application again become nonresponsive. It seems to be due to the execution of line #1 if condition.
Attempt to access member of System.Windows.Forms.Control from different thread than UI thread will cause cross-thread exception. If there is no work for UI thread, then there are idle gaps that can be used by a not-UI related computing.
The reason is, Windows form controls are bound to the thread they are created in to achieve thread safety. To get around this, we can add code to check for InvokeRequired:
You can't access controls from any thread other than the UI thread they were created on. You could use Invoke to get round this, but in all honesty I'd dump most of that code as "not a good idea".
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.
Control.CheckForIllegalCrossThreadCalls = false;
More detail : http://dotnetstep.blogspot.in/2009/09/cross-thread-operation-not-valid.html
dataGridView1.Invoke(new Action(() => { dataGridView1.Rows.Add(row); }));
Note: For each call you have to do same thing.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With