我想運行一個後臺工作來更新一個列表框中的值從一個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
錯誤。
想法如何解決這個問題?只要程序運行,我只想運行列表框的更新。
內訪問GUI元素不要訪問GUI元素和調試看看你是否仍然在LoadPrescriptions – Adil
中得到什麼異常?請更好地解釋,因爲我沒有理解。我在LoadPrescription中評論了「for」,但我仍然得到錯誤。 –
我的意思是你在LoadPrescriptions方法中訪問一些Windows組合控件嗎? – Adil