I want to add items in combo box after getting a column from database table. To achieve performance I have placed this task in a newly created thread
for (int i = 0; i < dataTable.Rows.Count; i++)
{
comboBox.Items.Add(dataTable.Rows[i][0].ToString());
}
but it gives the following exception:
"Cross thread operation not valid"
I searched for it and tried to solve this problem with the help of different methods, delegates. I tried to pass the whole dataTable to another method but couldn't solve the problem.
Please tell me how do I solve it?
Simply wrap the code in a delegate passed to BeginInvoke:
comboBox.BeginInvoke(
(Action)(() =>
{
for (int i = 0; i < dataTable.Rows.Count; i++)
{
comboBox.Items.Add(dataTable.Rows[i][0].ToString());
}
}));
This way you are forwarding the updates to the GUI thread, because it's the only thread allowed to make changes on the GUI.
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