回想一下backgroundWorker1.DoWork事件方法 - 程序异常

时间:2014-01-16 12:44:49

标签: c# winforms backgroundworker

我在winforms应用程序中有后台工作程序从数据库加载数据。

方法注册:

backgroundWorker1.WorkerReportsProgress = true;
backgroundWorker1.DoWork += backgroundWorker1_DoWork;
backgroundWorker1.RunWorkerCompleted += backgroundWorker1_RunWorkerCompleted;
backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;

方法定义:

  private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
   {
       if (!backgroundWorker1.CancellationPending)
       {
           Ctransakcja obj = (Ctransakcja)e.UserState;
           string[] row = new string[] { obj.id.ToString(), obj.tytul, obj.kwota, obj.nrkonta,obj.bank };
           dataGridView2.Rows.Add(row); 
       }
   }

   private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
   {

       button1.Enabled = true;

   }

private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
   {
       Ctransakcja obj = (Ctransakcja)e.Argument;
       LoadData(obj);
   }

    //funkcja ladujaca dane z bazy
   public void LoadData(Ctransakcja obj)
   {
       string CmdString;
       SqlCommand cmd;
       SqlDataReader reader;

      try
     {
           using (kd.con)
           {
               if (kd.con.State == ConnectionState.Closed)
                   kd.con.Open();
               CmdString = "SELECT * from TRANSAKCJE";
               cmd = new SqlCommand(CmdString, kd.con);
               reader = cmd.ExecuteReader();
               int i = 0;
               while (reader.Read())
               {
                   obj.id = int.Parse(reader[0].ToString());
                   obj.tytul = reader[1].ToString();
                   obj.kwota = reader[2].ToString();
                   obj.nrkonta = reader[3].ToString();
                   obj.bank = reader[4].ToString();
                   //dodanie danych itd
                   backgroundWorker1.ReportProgress(i, obj);
                   i++;
                   Thread.Sleep(10);
               }

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

和按钮点击事件方法

private void button1_Click(object sender, EventArgs e)
{
           dataGridView2.DataSource = null;
           dataGridView2.Refresh();

           Ctransakcja obj = new Ctransakcja(0, "", "", "", "");

           if (!backgroundWorker1.IsBusy)
           {

               backgroundWorker1.RunWorkerAsync(obj);

               button1.Enabled = false;

               button1.Text = "Loading...";
           }
}

这有效但在加载数据后我得到异常:连接String属性尚未初始化。

在调试器模式下,我注意到LoadData方法再次调用!!然后我得到例外。

由于

0 个答案:

没有答案