2

我从 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对于任何行。如果我检查前 2 行。然后valid=true只针对第一行。如果我检查前 3 行。然后valid=true只针对前两行。似乎最后一行总是未选中。但它被检查了。这不仅是我从头开始检查的时候。

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

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

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

4

1 回答 1

3

好的,我找到了导致这种行为的原因。当我得到他的价值时,最后选中的复选框仍处于编辑模式(bool)dgvInputFile.Rows[currentRow].Cells["boolCol"].FormattedValue

Insted 我应该使用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.
于 2015-06-02T08:10:23.083 回答