如何让所有这些代码在后台工作者下工作

时间:2013-06-23 09:52:28

标签: c# sql datagridview progress-bar backgroundworker

现在我有了这段代码:

private void button1_Click(object sender, EventArgs e)  
{
  OpenFileDialog openFileDialog1 = new OpenFileDialog();

    var dialogResult = openFileDialog1.ShowDialog();
    string sWybranyPlik;
    if (dialogResult  == DialogResult.OK)
    {
      sWybranyPlik = openFileDialog1.FileName;

      try
      {


        System.Data.OleDb.OleDbConnection ExcelConnection = new System.Data.OleDb.OleDbConnection("provider=Microsoft.ACE.OLEDB.12.0;Data Source='" + sWybranyPlik + "';Extended Properties=Excel 8.0;"); 

        System.Data.OleDb.OleDbDataAdapter OleDBAdapter = new System.Data.OleDb.OleDbDataAdapter("select * from [Tabelle1$]", ExcelConnection);

        DtSet.Clear();


        //wypełnianie datagridview
        OleDBAdapter.Fill(DtSet.Tables[0]);
        dataGridView1.DataSource = DtSet.Tables[0];


        //kasowanie starych danych w bazie danych
        string deletesql = @"DELETE FROM TabelaProdukty";
        System.Data.SqlServerCe.SqlCeCommand comDelete = new System.Data.SqlServerCe.SqlCeCommand(deletesql, sqlconnection);
        sqlconnection.Open();
        comDelete.ExecuteNonQuery();
        sqlconnection.Close();


        backgroundWorker1.RunWorkerAsync(); 
        progressform.ShowDialog();



        ExcelConnection.Close();
      }

      catch (Exception ex)
      {
        MessageBox.Show(ex.ToString());
      }
    }
} 

在_DoWork:

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{

  //wprowadzanie nowych danych z datagridview do bazy danych
  string strQuery = @"INSERT INTO TabelaProdukty VALUES (@VD, @ItemCode, @Item, @Qty, @Ppcur, @StandardPrice, @CeMarked, @Description, @Description2, @Edma)";
  sqlconnection.Open();
  using (System.Data.SqlServerCe.SqlCeCommand comm = new System.Data.SqlServerCe.SqlCeCommand(strQuery, sqlconnection))
  {
    comm.Parameters.Add("@VD", SqlDbType.NVarChar);
    comm.Parameters.Add("@ItemCode", SqlDbType.NVarChar);
    comm.Parameters.Add("@Item", SqlDbType.NVarChar);
    comm.Parameters.Add("@Qty", SqlDbType.NVarChar);
    comm.Parameters.Add("@Ppcur", SqlDbType.NVarChar);
    comm.Parameters.Add("@StandardPrice", SqlDbType.NVarChar);
    comm.Parameters.Add("@CeMarked", SqlDbType.NVarChar);
    comm.Parameters.Add("@Description", SqlDbType.NVarChar);
    comm.Parameters.Add("@Description2", SqlDbType.NVarChar);
    comm.Parameters.Add("@Edma", SqlDbType.NVarChar);

    for (int i = 0; i < dataGridView1.Rows.Count; i++)
    {

      comm.Parameters["@VD"].Value = dataGridView1.Rows[i].Cells["VD"].Value.ToString().Trim();
      comm.Parameters["@ItemCode"].Value = dataGridView1.Rows[i].Cells["ItemCode"].Value.ToString().Trim();
      comm.Parameters["@Item"].Value = dataGridView1.Rows[i].Cells["ITEM"].Value.ToString().Trim();
      comm.Parameters["@Qty"].Value = dataGridView1.Rows[i].Cells["QUANTITY"].Value.ToString().Trim();
      comm.Parameters["@Ppcur"].Value = dataGridView1.Rows[i].Cells["PPCUR"].Value.ToString().Trim();
      comm.Parameters["@StandardPrice"].Value = dataGridView1.Rows[i].Cells["STANDARD_SELL_PRICE"].Value.ToString().Trim();
      comm.Parameters["@CeMarked"].Value = dataGridView1.Rows[i].Cells["CE-MARKED"].Value.ToString().Trim();
      comm.Parameters["@Description"].Value = dataGridView1.Rows[i].Cells["ITEM_DESCRIPTION"].Value.ToString().Trim();
      comm.Parameters["@Description2"].Value = dataGridView1.Rows[i].Cells["ITEM_DESCRIPTION2"].Value.ToString().Trim();
      comm.Parameters["@Edma"].Value = dataGridView1.Rows[i].Cells["EDMA"].Value.ToString().Trim();


      comm.ExecuteNonQuery();

      backgroundWorker1.ReportProgress(i);

      if (backgroundWorker1.CancellationPending)
      {
        e.Cancel = true;
        break;
      }

    }
    sqlconnection.Close();


  }
}

正如你所看到的,这段代码让我选择一个带有OpenFileDialog的excel文件,清除DataSet,用数据填充数据集和datagridview,清除SQL表nad然后打开一个带有进度条的表单,显示复制数据的漫长过程从datagridview到sql数据库(12列中大约150000行)。 此时它可以正常工作。我遇到的问题是打开progressform之前的所有内容都需要时间,所以我想把它全部放在后台工作者之下,并在progressform中显示状态报告,如“旧数据被删除”或表“加载新数据”,然后运行进度条对于dgv-&gt; sql部分。不幸的是,将此代码放在_DoWork下我会得到不同的错误,具体取决于我在那里复制多少代码(所有button1_Click或仅“try”部分)。

你有什么想法吗?

致以最诚挚的问候,

编辑:

其他方法:

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{

  progressform.progressBar1.Value = e.ProgressPercentage;
}

private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
  if (e.Cancelled)
  {
    MessageBox.Show("Operacja przerwana! Cennik nie został wprowadzony w całości", "Uwaga!", MessageBoxButtons.OK, MessageBoxIcon.Warning);


  }
  else
  {

    progressform.label1.Text = "Zakończono pomyślnie! :)";
    progressform.button1.Enabled = true;
  }
}

1 个答案:

答案 0 :(得分:1)

您需要使用背景工作者的reportProgress事件。

openfiledialog中的文件名保存在实例级别的字符串中,即在方法之外。现在转移代码以在dataset eventhandler中完全填充backgroundworker.dowork。填充dataset电话backgroundworker.ReportProgress后。这将触发backgroundworker.ProgressChanged事件。在此方法中填充datagridview,因为此方法将在实例化后台工作程序的线程上调用。现在,使用dowork方法发送其余的ADO连接代码。这应该足够了。

**EDIT**

class YourClass
    {
        string filePath;
        DataSet dataset;
        private static void Do_Work(object sender, DoWorkEventArgs e)
        {
            //populate dataset
            //call worker.ReportProgress to trigger worker.ProgressChanged 
            //rest of time consuming ADO.Net Codes and other codes you wrote in your DoWork method
        }

        private static void Progress_Changed(object sender, ProgressChangedEventArgs e)
        {
            //this method is invoked in the thread where background worker is instantiated.
            //do all UI stuff here like populating datagridview from dataset
        }
    }