2017-07-03 89 views
1

從datagridview中的數據庫中獲取數據後,重複上次的數據,但遺漏了datagridview中的第一個數據。我請點擊此鏈接https://www.mindstick.com/Articles/1148/datagrid-using-backgroundworker-c-sharp在C#中使用backgroundworker在datagridview中獲取數據庫數據

 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) 
    { 
     RetriveTableData Obj = (RetriveTableData)e.Argument; 

     string SqlcmdString = "SELECT * from tblBook"; 

     SqlDataReader reader; 
     int i = 1; 
     try 
     { 
      using (SqlConnection conn = new SqlConnection(connectionString)) 
      { 
       Sqlcmd = new SqlCommand(SqlcmdString, conn); 
       conn.Open(); 
       reader = Sqlcmd.ExecuteReader(); 

       if (reader.HasRows) 
       { 
        while (reader.Read()) 
        { 
         //int.Parse(reader["NO_IND"].ToString()); 
         // Obj.EmpId = reader["C_FICH"].ToString(); 
        // Obj.EmpName = reader["C_SITE"].ToString(); 
         Obj.AccessionNo = reader["accessionNo"].ToString(); 
         Obj.Author = reader["author"].ToString(); 

         Thread.Sleep(100); 
         // To Report progress. 
         backgroundWorker1.ReportProgress(i, Obj); 

         if (backgroundWorker1.CancellationPending) 
         { 
          // Set the e.Cancel flag so that the WorkerCompleted event 
          // knows that the process was cancelled. 
          e.Cancel = true; 
          backgroundWorker1.ReportProgress(0); 
          return; 
         } 
         i++; 
        } 
        conn.Close(); 
       } 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
    } 

    public class RetriveTableData 
    { 
     public string AccessionNo; 
     public string Author; 
    } 

    private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) 
    { 
     if (!backgroundWorker1.CancellationPending) 
     { 
      //Gets the user state that is sent as part of ReportProgress() Method from DoWork Event 
      RetriveTableData Obj = (RetriveTableData)e.UserState; 
      //Add the data to the dataGridView1 
      dataGridView1.Rows.Add(Obj.AccessionNo.ToString(), Obj.Author.ToString()); 
      progressBar1.Value = e.ProgressPercentage; 
      label1.Text = "Processing row.. " + e.ProgressPercentage.ToString() + " of " + TotalRecords; 
     } 

    } 
    private int GetTotalRecords() 
    { 
     SqlConnection con; 
     SqlCommand cmd; 
     try 
     { 
      using (con = new SqlConnection(connectionString)) 
      { 
       cmd = new SqlCommand("SELECT COUNT(*) FROM tblBook", con); 
       con.Open(); 
       TotalRecords = int.Parse(cmd.ExecuteScalar().ToString()); 
       con.Close(); 
      } 
     } 
     catch (Exception ex) 
     { 
      MessageBox.Show(ex.Message); 
     } 
     return TotalRecords; 
    } 

    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) 
    { 

     if (e.Cancelled) 
     { 
      label1.Text = "Cancelled by User Intentionally..."; 
     progressBar1.Value = 0; 
     } 
     // Check to see if an error occurred in the background process. 
     else if (e.Error != null) 
     { 
      label1.Text = e.Error.Message; 
     } 
     else 
     { 
      // BackGround Task Completed with out Error 
      label1.Text = " All Records Loaded..."; 
     } 
    } 

    private void button1_Click(object sender, EventArgs e) 
    { 
     // statusStrip1.Visible = true; 
     // toolStripStatusLabel1.Visible = true; 


     dataGridView1.ColumnCount = 2; 
     dataGridView1.Columns[0].Name = "Access No."; 
     dataGridView1.Columns[0].Width = 150; 
     dataGridView1.Columns[1].Width = 150; 
     dataGridView1.RowHeadersWidth = 21; 
     dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing; 
     dataGridView1.ColumnHeadersHeight = 23; 
     dataGridView1.Columns[1].Name = "Author"; 


     progressBar1.Maximum = GetTotalRecords(); 

     if (!backgroundWorker1.IsBusy) 
     { 
      RetriveTableData TObj = new RetriveTableData(); 
      dataGridView1.Rows.Clear(); 
      // Start the BackGround Thread to Execute 
      backgroundWorker1.RunWorkerAsync(TObj); 
      // btStart.Enabled = false; 
      //btCancel.Enabled = true; 
     } 

    } 

我得到這個輸出,其中第一資訊:1122錯過了,重複最後一個數據PEC-5281。由於我的低級我不能張貼圖像,所以我把鏈接,你可以查看輸出。

https://krishnas.com.np/2.PNG

+0

你只有1個Obj,並且你以奇怪的方式得到它。 –

+0

這是什麼意思。我不明白你回覆 –

+0

你必須在while循環中創建一個新的obj。 –

回答

0

你需要創建對象的集合的每一行NAD然後使用該集合作爲DataGridView

數據源有了async-await這是可以做到的小出價更清晰,而不會被BackgroundWorker

創建額外的線程
private async Task<IEnumerable<RetriveTableData>> GetDataAsync() 
{ 
    var query = "SELECT * from tblBook"; 
    using (var connection = new SqlConnection(connectionString)) 
    using (var command = new SqlCommand(query, connection)) 
    { 
     await connection.OpenAsync(); 
     using (var reader = command.ExecuteReaderAsync()) 
     { 
      var data = new List<RetriveTableData>(); 
      while(await reader.ReadAsync()) 
      { 
       var temp = new RetriveTableData 
       { 
        EmpId = reader["C_FICH"].ToString(); 
        EmpName = reader["C_SITE"].ToString(); 
        AccessionNo = reader["accessionNo"].ToString(); 
        Obj.Author = reader["author"].ToString(); 
       }; 

       data.Add(temp); 
      } 

      return data; 
     } 
    } 
} 

然後,例如在Form.Load事件處理程序中,您可以加載數據。

private async void Form_Load(object sender, EventArgs e) 
{ 
    dataGridView1.DataSource = await GetDataAsync(); 
} 
相關問題