Nalaka526
Nalaka526

Reputation: 11464

Error when reading ComboBox values within BackgroundWorker DoWork event

When I acces Form controls within BackgroundWorker DoWork event, it reads values from DatePicker but not from TextBox or ComboBox

Error:

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

enter image description here

Code :

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

        string strProgram = cmbProgram.Text;

    }

How does it read values from DataPicker (in a different thread)?

Is there any workaround to access Form Controls from BackgroundWorker DoWork Event?

Upvotes: 1

Views: 3194

Answers (3)

Devator
Devator

Reputation: 3904

You can pass it as an argument. For example:

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

And grab the contents in the doWork with

string Item = e.Argument.ToString();

Upvotes: 1

jrb
jrb

Reputation: 1728

Use:

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

           }));

Upvotes: 2

Martin Moser
Martin Moser

Reputation: 6269

You cannot access a control from a different thred. The usual way of getting around that problem is to read the current value from the UI thread, and then pass the value to the second thread (or BackgroundWorker).

You can disable the check by setting CheckForIllegalCrossThreadCalls on the control class to false, but be advised you don't want to do this.

Upvotes: 2

Related Questions