2012-05-04 27 views
1

當我存取權限內BackgroundWorkerDoWork事件表單控件,它的DatePicker讀值,但不能從文本框組合框錯誤的BackgroundWorker的DoWork事件中讀取組合框的值時

錯誤:

Cross-thread operation not valid: Control 'cmbProgram' accessed from a thread other than the thread it was created on. 

enter image description here

代碼:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
    { 
     string strDate = dtpDate.Value.ToString(); 

     string strProgram = cmbProgram.Text; 

    } 

它是如何讀取DataPicker值(在不同的線程)?

有任何解決方法從BackgroundWorkerDoWork事件訪問窗體控件​​?

回答

2

用途:

Dispatcher.Invoke(new Action(() => 
      { 
       string strDate = dtpDate.Value.ToString(); 
       string strProgram = cmbProgram.Text; 

      })); 
2

您無法訪問來自其他項目的控件。 解決該問題的常用方法是從UI線程讀取當前值,然後將值傳遞給第二個線程(或BackgroundWorker)。

您可以在控制類CheckForIllegalCrossThreadCalls設置爲false禁用檢查,但被告知你不希望這樣做。

1

你可以把它作爲一個參數。例如:

backgroundworker1.RunWorkerAsync(comboBox1.SelectedItem.ToString()); 

而且搶在doWork內容與

string Item = e.Argument.ToString(); 
相關問題