自动更新C#列表框

时间:2012-05-06 06:32:44

标签: c# winforms backgroundworker auto-update

我想运行后台工作程序来使用mssql数据库中的值更新列表框。我出来了:

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

在(1)和(2)之间的某处我得到A first chance exception of type 'System.InvalidOperationException' occurred in System.Windows.Forms.dll 错误。

关于如何解决这个问题的想法?我只想在程序运行时运行列表框的更新。

1 个答案:

答案 0 :(得分:2)

当我们从线程访问某些GUI控件时,GUI会进入这种情况

尝试访问此委托结构中的GUI元素

        MethodInvoker objMethodInvoker = delegate
        {
             //access and assign data to list control here               
        };
        if (InvokeRequired)
            BeginInvoke(objMethodInvoker);
        else
            objMethodInvoker.Invoke();