如何将结果发送到DoWork中的主线程(BackgroundWorker)

时间:2019-09-25 05:47:30

标签: c# sql-server winforms datatable backgroundworker

我对BackgroundWorker有疑问!当我从数据库获取数据并尝试将数据传输到RunWorkerCompleted时,出现错误:

  

System.NullReferenceException对对象的引用并不表示对象e的实例为空。

问题出现在e.Result = dataTable;

private void BackgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)   
{
        string Refresh = "dbo.GetRenderedService '" + dateTimePicker2.Value.Date.ToString() + "','" + dateTimePicker4.Value.Date.ToString() + "'";
        DataTable dataTable = DbConnection.DBConnect(Refresh);
        int i = 1;
        try
        {enter code here
            foreach (DataRow dr in dataTable.Rows)
            {
                backgroundWorker1.ReportProgress(i);
                Thread.Sleep(100);
                i++;
            }
            e.Result = dataTable;
        }
        catch(Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

private void BackgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progBar.Value = e.ProgressPercentage;
}

private void BackgroundWorker1_RunWorkerCompleted(object sender, System.ComponentModel.RunWorkerCompletedEventArgs e)
{
        source.DataSource = e.Result;
        dataGridView1.DataSource = source;
        dataGridView1.Columns[0].Visible = false;
        dataGridView1.Columns[1].Visible = false;
        dataGridView1.Columns[2].Visible = false;
        dataGridView1.Columns[3].Visible = false;
        dataGridView1.Columns[4].Visible = false;
        dataGridView1.Columns[5].Visible = false;
        dataGridView1.Columns[6].Visible = false;
}

这是用于从SQL Server提取数据的类。

class DbConnection
{
    public static string connectionString = "Data Source=POTITPC-01\\PLMLOCAL;Initial Catalog=Batys;User ID=sa;Password=!sql123;";
    public static DataTable DBConnect(string query)
    {
        SqlConnection conn = new SqlConnection(connectionString);
        SqlDataAdapter da = new SqlDataAdapter(query, conn);
        DataTable dataTable = new DataTable();

        try
        {
            conn.Open();
            da.Fill(dataTable);
            conn.Close();
            conn.Dispose();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
        return dataTable;
    }

0 个答案:

没有答案