简体   繁体   中英

populate combobox c# in the background

I'm doing a project in Visual Studio 2013 using Windows Forms .

I have a couple of forms ( LogIn , Meny , FakturaSokning (For now))

When you start the program you open the LogIn and when you log in you go to the Meny where you can open the FakturaSokning .

Now to the problem i have. I have 2 comboBoxes named comboBoxFaktNr1 and comboBoxFaktNr2 and I'm trying to populate them with the FaktNr i get from a SQL server. I connect to the server with

MigrateDBFakturaEntities db = new MigrateDBFakturaEntities();

and get the relevent information whith

var t = db.Fakturor.OrderBy(z => z.FaktNr).ToList();

the first thing i tried was doing a foreach loop

foreach (var item in t)
{
     comboBoxFaktNr1.Items.Add(item.FaktNr);
}

witch works but the problem with this was that it stopped responding untill it was done.

How can i have it eather fill the comboboxes in the background when opening the FakturaSokning Form and auto update the comboboxes when its done or do it when eather in the Meny or LogIn form?

If i missed some relative information tell me and i will try adding it as soon as possible.

You can try using the Backgroundworker which executes the operation on a seperate thread.

Backgroundworker MSDN

This seamd to have been the problem. Also the problem i had when trying to use it earlier was that i tried to make and use the worker manualy by code. But if i used the ToolBox and added a worker from there everything worked. And this is the code i used in the DoWork

BackgroundWorker worker = sender as BackgroundWorker;

                List<Fakturor> t = db.Fakturor.OrderBy(z => z.FaktNr).ToList();

                foreach (var item in t)
                {
                    comboBoxFaktNr1.Invoke((Action)(() =>
                        {
                            comboBoxFaktNr1.Items.Add(item.FaktNr);
                        }));

                }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM