Pergunta

In my backgroundworker, it need to call methods from another class come with out parameter.

[Class 1]

    public partial Class1 : Form
    {
        private void bw_DoWork(object sender, DoWorkEventArgs e)
        {
            DataGridView gv;
            int param1, param2;

            Class2 class2 = new Class2();
            class2.method(gv, out param1, out param2);
        }
    }

[Class 2]

    public Class2
    {
        public void method(DataGridView gv, out int param1, out int param2)
        {
            param1 = 0;
            param2 = 0;

            // basically grab the data in dataGridView and load into database
        }
    }

How should i correctly call Class2.method without the error Cross-thread operation not valid: 'class2' accessed from a thread other than the thread it was created?

Foi útil?

Solução

You cannot edit/modify Forms or user controls on threads on which they were not created. In order to do this, you'll need to extract the data you need from the DataGridView on the UI thread, and put that into a data structure (like a DataTable for example) that isn't a control or form (or pass it in to the background worker as an argument). Then retrieve your data from that data structure in your background thread, and add it to the DB.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top