如何从backgroundWorker_DoWork结果

时间:2015-09-30 20:10:45

标签: c# visual-studio datagridview

我正在尝试在数据集填满后填充数据网格视图,但是我收到了这个错误:

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

这是我的代码,它似乎工作一次然后不再工作。我不是100%确定交叉线程意味着什么,因为我是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];
            }
        }
    }
}

1 个答案:

答案 0 :(得分:2)

这个答案:Cross-thread operation...很好地回答了你的问题

对于您的具体情况,这应该适合您:

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