【问题标题】:Not getting all rows when iterating through DataGridView rows遍历 DataGridView 行时未获取所有行
【发布时间】:2014-11-21 03:14:35
【问题描述】:

在 VB.NET WinForms 应用程序中,我有一个带有复选框的 DataGridView 作为第一列中的非绑定列。我需要将选中复选框的每一行添加到行集合中。

我正在使用下面的代码遍历行并找到带有选中复选框的行:

For Each row As DataGridViewRow In dgvEmployees.Rows

    Dim chkCell As DataGridViewCheckBoxCell = DirectCast(row.Cells(0), DataGridViewCheckBoxCell)
    If Convert.ToBoolean(chkCell.Value) = True Then
        Console.WriteLine("This should be the Emp No of the checked row: " & row.Cells(1).Value.ToString())
    End If

Next

但它缺少带有选中复选框的最后一行。 IE。如果我选中三个复选框,在控制台输出中我会看到前两个选中行的“Emp No”。

认为这就像零索引的问题,我还尝试进行使用计数器的迭代:

For rowNum As Integer = 0 To dgvEmployees.Rows.Count - 1
    Dim currentRow As DataGridViewRow = dgvEmployees.Rows(rowNum)
    Dim chkCell As DataGridViewCheckBoxCell = DirectCast(currentRow.Cells(0), DataGridViewCheckBoxCell)

    If Convert.ToBoolean(chkCell.Value) = True Then
        Console.WriteLine("This should be the emp no of the checked row: " & currentRow.Cells(1).Value.ToString())
    End If

Next

但是我得到了与该代码相同的行为。我尝试围绕 Integer = 0 和 Rows.Count - 1 等进行更改,但这也无济于事。

如果重要,DataGridView 的 SelectionMode 需要设置为 CellSelect。

更新

在填充数据网格视图的表中有 694 条记录。

我添加了一个控制台输出来获取 rows.count 值:

Console.WriteLine("Num rows: " & dgvEmployees.Rows.Count)

得到 695,这是有道理的,因为 datagridview 中的最后一行允许输入新行。 (但我会认为第二种迭代方法中的 Count - 1 会解释这一点。)

我也加了

Console.WriteLine("Row index: " & chkcell.RowIndex)

就在如果检查复选框之前,并且选中了第一、第三和第五行(索引 0、2、4),输出如下:

Num rows: 695
Row index: 0
this should be the emp no of the checked row: ACS175
Row index: 1
Row index: 2
this should be the emp no of the checked row: AJAW03
Row index: 3
Row index: 4
Row index: 5
Row index: 6

在 Row index: 4 行之后应该有一个“this should be...”输出。

【问题讨论】:

  • 最后选中的行是网格中的最后一行吗?您能否使用调试器逐步检查 dgvEmployees.Rows.Count 的值是否与您在网格中看到的行数匹配?
  • @CaseyWilkins,谢谢你,我用迭代期间的行数和索引输出的详细信息更新了我的问题。
  • 您是否尝试过使用调试器单步执行前 5 或 6 次迭代,并在单步执行时检查 chkCell.Value?
  • 我刚刚做了,这是最奇怪的事情:我正在逐行迭代 For/Next 循环,当我到达带有最后一个复选框的行时(仍然使用上面的示例,所以我'm 在行索引 4) chkcell.Value 显示为 False,当该复选框被选中时。前两个复选框正确显示 True。 - 它总是最后一个被选中的复选框,评估结果为 False。
  • 选中最后一行的复选框后,您是否正在移动/单击另一行?当您检查最后一行时,听起来 datagridview 没有提交您的更改。尝试检查最后一行,然后单击任何其他行/单元格以移动焦点。然后单步执行您的代码并查看该值是否为真。

标签: vb.net winforms datagridview datagridviewrow


【解决方案1】:

您检查的最后一个复选框似乎没有被 DataGridView 提交,因为您在检查后没有将焦点移动到另一个单元格。在运行迭代代码之前试试这个:

If dgvEmployees.IsCurrentCellDirty Then
    dgvEmployees.CommitEdit(DataGridViewDataErrorContexts.Commit)
End If 

【讨论】:

  • 成功了,凯西。 (不过感觉有点像 hack)非常感谢您抽出宝贵的时间。
猜你喜欢
  • 2016-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-25
  • 2019-01-25
  • 1970-01-01
相关资源
最近更新 更多