0

I want to run a background worker to update a listbox with values from a mssql database. I came out with this :

    public frmMain()        {
        InitializeComponent();            
        bw.DoWork += new DoWorkEventHandler(bw_DoWork);
    }

    private void frmMain_Load(object sender, EventArgs e) {
            if (bw.IsBusy != true)
            {
                bw.RunWorkerAsync();
            }
     }

   private void bw_DoWork(object sender, DoWorkEventArgs e){
        BackgroundWorker worker = sender as BackgroundWorker;
        for (int i = 1; (i <= 10); i++) {
            if ((worker.CancellationPending == true)) {
                e.Cancel = true;
                break;
            }
            else                {
               (1) LoadPrescriptions();  //load the date in a list and writes the list into the listbox
               (2) System.Threading.Thread.Sleep(500);
            }
        }
    }


   private void LoadPrescriptions()
    {
        main_controller = new MainController();
        prescriptionsList = new List<Prescription>();
        prescriptionsList = main_controller.LoadPrescriptions(0); 
        lstPrescriptions.Items.Clear();
        for (int i = 0; i < prescriptionsList.Count; i++)
            lstPrescriptions.Items.Add(prescriptionsList[i].name + "  " + prescriptionsList[i].surname);
    }

Somewhere between (1) and (2) i get A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll error.

Ideas on how can i fix this ? I just want to run an update of the listbox for as long as the program is running.

sebastian.roibu
  • 2,579
  • 7
  • 37
  • 59

1 Answers1

2

When we access some GUI control from thread other then GUI we get into this sort of situation

Try to access the GUI element within this delegate structure

        MethodInvoker objMethodInvoker = delegate
        {
             //access and assign data to list control here               
        };
        if (InvokeRequired)
            BeginInvoke(objMethodInvoker);
        else
            objMethodInvoker.Invoke();
Adil
  • 146,340
  • 25
  • 209
  • 204
  • the update is working just fine. now i have to deal with an index out of range exception. – sebastian.roibu May 06 '12 at 07:03
  • Check if you are accessing some collection like array out of its size like accessing 4th element of array having size of three elements – Adil May 06 '12 at 07:09
  • i think there was an error in the program or something, because i don't get that error anymore. thanks a lot 4 your answers. – sebastian.roibu May 06 '12 at 07:34