2014-01-23 28 views
0

我使用以下代碼來獲取在datagridview中選擇的員工總數。 我希望它在用戶選中複選框或用戶取消選中時進行計算。將CellDirtyStateChanged事件與CheckBoxColumns一起使用

private void dgvEmployeesToProcess_CellDirtyStateChanged(object sender, EventArgs e) 
     { 
      try 
      { 
       if (dgvEmployeesToProcess.CurrentCell.ColumnIndex == 4) 
       { 
        txtNoOfEmpToProcess.Text = string.Empty; 

        int count = 0; 

        foreach (DataGridViewRow row in dgvEmployeesToProcess.Rows) 
        { 
         DataGridViewCheckBoxCell checkBox = (DataGridViewCheckBoxCell)row.Cells[4]; 

         if (Convert.ToBoolean(checkBox.Value) == true) 
         { 
          count = count + 1; 
         } 
        } 

        // show total count in textbox 
        txtNoOfEmpToProcess.Text = count.ToString(); 
       } 
      } 
      catch (Exception ex) 
      { 
       MessageBox.Show(ex.Message); 
      } 
     }  

我遇到的問題是,當我檢查行[0]中的複選框,即。第一個,checkBox.Value總是空,count = 0.當我點擊第二個複選框時,count = 1等等。 爲了使計數正確,我需要做些什麼?我需要使用CellDirtyStateChanged以外的東西嗎?

回答

1

dgvEmployeesToProcess_CellDirtyStateChanged開始加入這一行:

dgvEmployeesToProcess.CommitEdit(DataGridViewDataErrorContexts.Commit); 

這將提交更改(例如中選中/清除特定列),所以你會得到實際的結果。

相關問題