简体   繁体   中英

Auto update C# listbox

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.

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();

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