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

本文关键字:最后 复选框 datagridview | 更新日期: 2023-09-27 17:52:47

我从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

除了。如果我检查第一个,那么第二个,第三个和取消检查第三个工作良好

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

好的,我找到了导致这种行为的原因。最后选中的复选框仍处于编辑模式时,我得到他的值与(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.