Using Background worker to fill multiple comboboxes

Posted on 2014-10-26
Medium Priority
Last Modified: 2014-11-16
I have a basic understanding of background worker.  The issue I am having is I do not know how to fill multiple comboboxes in the background worker.  I can fill 1, but when it comes to multiple, the only way I know to do is create multiple background workers.  Any help is greatly appreciated!!  I am using VB.NET not C

 Private Sub BackgroundWorker1_DoWork(ByVal sender As System.Object, ByVal e As System.ComponentModel.DoWorkEventArgs) _
    Handles BackgroundWorker1.DoWork

        Dim sqluname As String
        Dim sqlpass As String
        Dim sqlseverlocation As String
        Dim sqltable As String
        Dim commtable, communits, commadvisory, commguidecard, commholdingcalls, commdispatchedunits, commclosedcall, commlocation, commstreet, commcity, commactivitycode, commstate, commmethod, commagency, commbolotype, commpaginggroup, Commpagingindividual As String

        If (IO.File.Exists(configfilefromcad)) Then

            'create a new xmltextreader object
            'this is the object that we will loop and will be used to read the xml file
            Dim document As XmlReader = New XmlTextReader(configfilefromcad)

            'loop through the xml file
            While (document.Read())

                Dim type = document.NodeType

                'if node type was element
                If (type = XmlNodeType.Element) Then

                    'if the loop found a <SQLUserName> tag
                    If (document.Name = "SQLUserName") Then

                        sqluname = Decrypt(document.ReadInnerXml.ToString())

                    End If

                    'if the loop found a <SQLPassword> tag
                    If (document.Name = "SQLPassword") Then

                        sqlpass = Decrypt(document.ReadInnerXml.ToString())

                    End If

                    'if the loop found a <SQLServerLocation> tag
                    If (document.Name = "SQLServerLocation") Then

                        sqlseverlocation = Decrypt(document.ReadInnerXml.ToString())

                    End If

                    'if the loop found a <SQLTableName> tag
                    If (document.Name = "SQLTableName") Then

                        sqltable = Decrypt(document.ReadInnerXml.ToString())

                    End If

                    If (document.Name = "AgencyName") Then
                        Dim titlename As String
                        titlename = Decrypt(document.ReadInnerXml.ToString())

                        Me.Text = "Employee Management - " & titlename & " - " & System.Reflection.Assembly.GetExecutingAssembly.GetName.Name()

                    End If

                End If
            End While

        End If

        Dim cn As New SqlConnection("Server='" + sqlseverlocation + "';Initial Catalog='" + sqltable + "';Persist Security Info=True;User ID='" + sqluname + "';Password='" + sqlpass + "'")

        Dim adap1 As New SqlDataAdapter("Select TextToAdd FROM tblComboBoxEdit WHERE ComBoxNameEdit='Race'", cn)

        Dim dt1 As New DataTable


        Dim Unit = dt1.AsEnumerable().Select(Function(d) DirectCast(d(0).ToString(), Object)).ToArray()

       Me.BackgroundWorker1.ReportProgress(0, Unit)


    End Sub

    Private Sub BackgroundWorker1_ProgressChanged(ByVal sender As System.Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs)   Handles BackgroundWorker1.ProgressChanged


    End Sub

Open in new window

Question by:russell12
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 40
ID: 40405828
You have it right. A BackgroundWorker can do only one thing at a time, so you need many of them if you want to do many jobs at the same time.

Author Comment

ID: 40409600
Thank you for your input.  I read online that too many background workers can cause a good deal of lag.  I have about 10 comboboxes that need to be filled at Form_Load.  Do you know if this is a true statement?  I have found a work around, but it is not a "good" work around.  I am using the background thread to work with the gui and update a label.  Thank you for your input.
LVL 40

Assisted Solution

by:Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger) earned 668 total points
ID: 40409822
Yes you will feel the lag. A BackgroundWorker is just an easy way to start a new thread. Each BackgroundWorker starts its own thread.

A computer can do only one thing at a time, unless something in the program manages the use of multiple cores in modern processors, which as far as I know the compiler does not do automatically.

Since it does one thing at a time, in order to make the threads run in parallel, the computer simply allows little slots of time to each one in turn. This involves more work, because it needs to reminds where each thread is paused in order to restart from the right place it when its turn comes again. This switching between threads slows down things.

Using numerous threads (BackgroundWorkers) always slows down things. You never use that to speed up things, but only to give the impression that things are going faster. The name given to the control says it all. You use that for background work, not for work that happens in the forefront. For instance, if the form has its multiple ComboBoxes on different tabs, you could first load the ones on the tab that shows first. Then, while the user is working on that tab, use a BackgroundWorker to load the tabs that are not shown yet. That way the first tab shows fast because it does not have to wait for all the other ones to be ready. The user being a lot slower than the computer, he won't feel the slow down created by the BackgroundWorkers while they fill the other tabs. But when he switches to another tab, it's very fast because it was already loaded in the background.

If all the ComboBoxes are on the same tab, form, page, you lose by using BackgroundWorkers. If the user always perform the same sequence of operations, you might want to load the portion of the data that he uses first, and load the rest with a BackgroundWorker while he starts working, keeping the controls disabled until they are ready to work. But if all the information has to be available right from the start, they you are better to do the job sequentially.

One thing you can do then, to give the impression that things are going faster, is to show something on the screen while you are loading your form. A simple MessageBox, or maybe better, a splash screen. When the users sees something, he fills that the computer is working. Otherwise, he is only waiting and it seems to take long.
Get your Disaster Recovery as a Service basics

Disaster Recovery as a Service is one go-to solution that revolutionizes DR planning. Implementing DRaaS could be an efficient process, easily accessible to non-DR experts. Learn about monitoring, testing, executing failovers and failbacks to ensure a "healthy" DR environment.

LVL 83

Accepted Solution

CodeCruiser earned 668 total points
ID: 40411256
If all your comboboxes require the amount of code that you currently have in your backgroundworker, I would suggest adding a method for populating each combobox and then calling those methods from the same backgroundworker.
LVL 28

Assisted Solution

Ark earned 664 total points
ID: 40415383
As I can see you'r using ReportProgress vs ProgressChange Event to fill combobox. e.UserState is an object backgroundworker pass to gui. Now you'r using an array of object, but it can be ANY type, for example a dictionary:
Inside bgworker_dowork:
Dim dict As New Dictionary(Of String,Object())
dict.Add(MyFirstComboName, dt1.AsEnumerable().Select(Function(d) DirectCast(d(0).ToString(), Object)).ToArray())
dict.Add(MySecondComboName, dt2.AsEnumerable().Select(Function(d) DirectCast(d(0).ToString(), Object)).ToArray())
'or whatever data to fill each combo

Open in new window

Then, in _ProgressChanged event
Dim dict = CType(e.UserState, Dictionary(Of String, Object()))
For Each key in dict.Keys
    Dim cbo As ComboBox = Me.Controls(key) 

Open in new window


Author Closing Comment

ID: 40445926
Sorry for taking so long to repsond.  Thanks for all of your help!

Featured Post

Enroll in August's Course of the Month

August's CompTIA IT Fundamentals course includes 19 hours of basic computer principle modules and prepares you for the certification exam. It's free for Premium Members, Team Accounts, and Qualified Experts!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Many of us here at EE write code. Many of us write exceptional code; just as many of us write exception-prone code. As we all should know, exceptions are a mechanism for handling errors which are typically out of our control. From database errors, t…
More often than not, we developers are confronted with a need: a need to make some kind of magic happen via code. Whether it is for a client, for the boss, or for our own personal projects, the need must be satisfied. Most of the time, the Framework…
NetCrunch network monitor is a highly extensive platform for network monitoring and alert generation. In this video you'll see a live demo of NetCrunch with most notable features explained in a walk-through manner. You'll also get to know the philos…
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question