未选中 datagridview 复选框列中最后选中的行

Last checked row in datagridview checkbox column is not checked

我从 excel 文件中填充了 DataGridView。 我将复选框列添加到此 datagridview

...
dtSet.Tables[0].Columns.Add(new DataColumn("boolCol", typeof(bool)));
dgvInputFile.DataSource = dtSet.Tables[0];
dgvInputFile.AllowUserToAddRows = false;

稍后我会检查是否每一行都被检查过:

  for (int currentRow = 0; currentRow < grv.Rows.Count; currentRow++)
  {
   DataGridViewCheckBoxCell CbxCell = dgvInputFile.Rows[currentRow].Cells["boolCol"] as DataGridViewCheckBoxCell;
   bool valid = CbxCell != null && !DBNull.Value.Equals(CbxCell.Value) && (bool)CbxCell.Value == true; 
    ....

如果我检查第一行。然后 valid=false 用于任何行。 如果我检查前两行。然后 valid=true 仅用于第一行。 如果我检查前 3 行。然后 valid=true 仅用于前两行。 似乎最后一行总是未选中。但是它被检查了。这不仅是我从头开始检查的时候。

我尝试了第二种方法来确定该行是否被检查并且结果相同。

(bool)dgvInputFile.Rows[currentRow].Cells["boolCol"].FormattedValue

此外。如果我检查第一个,然后是第二个,然后是第三个并且 取消检查第三个 工作正常。

好的,我找到了导致此行为的原因。 当我用 (bool)dgvInputFile.Rows[currentRow].Cells["boolCol"].FormattedValue

获取他的值时,最后选中的复选框仍处于编辑模式

我应该使用 DataGridViewCell.EditedFormattedValue 属性.

MSDN

Gets the current, formatted value of the cell, 
regardless of whether the cell is in edit mode 
and the value has not been committed.