简体   繁体   中英

How to fill dataGrid view from backgroundWorker_DoWork Result

I'm trying to fill a datagridview after the data set has been filled but i get this error:

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

This is the code I have, it seems to work once and then not again. I'm not 100% sure what cross thread means, since I'm new to C#:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
    try
    {
        superset = new DataSet();
        string[] lines = BranchTBox.Lines;

        for (int i = 0; i < lines.Length; i++)
        {
            if (lines[i].Length == 7)
            {
                if (qachk.Checked == false)
                {
                    connectionString = "Database=" + lines[i] + "; Hostname=" + lines[i] + "." + lines[i] + ".xx; Port = xx; Protocol = xx; Uid=xxx; Pwd= xx;Connection Timeout=1";
                }
                else
                {
                    foreach (Control child in panel4.Controls)
                    {
                        if ((child as RadioButton).Checked)
                        {
                            qaserver = child.Text;
                        }
                    }
                    connectionString = "Database=" + lines[i] + "; Hostname=" + xx+ ".xx.xx; Port = xx; Protocol = TCPIP; Uid=xx; Pwd= xxx;;Connection Timeout=1";
                    connection = new OdbcConnection(connectionString);
                    adapter = new OdbcDataAdapter(masterquery, connection);
                    connection.Open();
                    adapter.Fill(superset);
                    superset.Merge(superset);
                    connection.Close();
                }
                dataGridView1.DataSource = superset;
                dataGridView1.DataSource = superset.Tables[0];
            }
        }
    }
}

This answer: Cross-thread operation... answers your question pretty well

For your specific case, this should work for you:

    dataGridView1.Invoke((Action)(() => dataGridView1.DataSource = superset));
    dataGridView1.Invoke((Action)(() => dataGridView1.DataSource = superset.Tables[0]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM