2012-05-06 50 views
0

我想運行一個後臺工作來更新一個列表框中的值從一個mssql數據庫中的值。我來到了這一點:自動更新C#listbox

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 錯誤。

想法如何解決這個問題?只要程序運行,我只想運行列表框的更新。

+0

內訪問GUI元素不要訪問GUI元素和調試看看你是否仍然在LoadPrescriptions – Adil

+0

中得到什麼異常?請更好地解釋,因爲我沒有理解。我在LoadPrescription中評論了「for」,但我仍然得到錯誤。 –

+0

我的意思是你在LoadPrescriptions方法中訪問一些Windows組合控件嗎? – Adil

回答

2

當我們訪問其他線程一些GUI控制則GUI我們進入這種情況

嘗試將此委託結構

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

更新工作正常。現在我必須處理索引超出範圍的異常。 –

+0

檢查你是否正在像訪問一些像數組這樣的數組的集合,比如訪問數組的第三個元素,這個數組的大小是三個元素 – Adil

+0

我認爲程序中有錯誤或者什麼,因爲我再也沒有那個錯誤了。非常感謝你的回答。 –