Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading data from database to combo box using another thread

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?

like image 911
Muhammad Ali Dildar Avatar asked Aug 01 '26 16:08

Muhammad Ali Dildar


1 Answers

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.

like image 55
Tudor Avatar answered Aug 03 '26 06:08

Tudor