【问题标题】:How to determine if one checkbox on a datagridview is checked and if all are unchecked如何确定是否选中了datagridview上的一个复选框以及是否全部未选中
【发布时间】:2017-09-18 22:22:11
【问题描述】:

我有一个 DataGridView,在第一列中包含复选框。

我需要检查是否只选中了一个复选框,或者是否没有选中任何复选框。

循环虽然 DataGridView 会给我 true 和 false,因为每个框都被选中和取消选中,这是我用下面的代码尝试的。

我需要创建一个方法,如果其中一个框被选中则返回 true,如果没有选中框则返回 false。

我试过这个:调用它和实验是不同的相关DataGridView点击事件。

Public Function IsContainChecked() As Boolean

    Dim ch1 As New DataGridViewCheckBoxCell()
    ch1 = DirectCast(DataGridView1.Rows(DataGridView1.CurrentRow.Index).Cells(0),  _
        DataGridViewCheckBoxCell)
    Return CBool(ch1.EditingCellFormattedValue)

End Function

【问题讨论】:

  • 为什么需要直接投射对象?
  • 不要new 只是为了在下一行重新分配它。最近看到的太多了。

标签: vb.net winforms


【解决方案1】:
Dim checkedCount = DataGridView1.Rows.
                                 Cast(Of DataGridViewRow)().
                                 Where(Function(row) Not row.IsNewRow).
                                 Count(Function(row) CBool(row.Cells(0).Value))

Select Case checkedCount
    Case 0
        'No rows are checked.
    Case 1
        'One row is checked.
    Case Else
        'More than one row is checked.
End Select

您可以将该代码放入一个方法中并在您喜欢的任何位置调用它,例如在CellValueChanged 事件处理程序中。请注意,复选框单元格的Value 在单击时不会立即更改。事件的文档解决了这个问题,并解释了如果您想强制 Value 在单击时更改该怎么做。

【讨论】:

  • 还有... 这如何解释 OP 的问题?在没有解释原始帖子的情况下抛出答案是无助的,因为 OP 不明白他们哪里有问题......
  • @Codexer,鉴于 OP 已经接受了答案,我想你可以问他们这个问题。
猜你喜欢
  • 2011-06-12
  • 2013-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 2013-09-10
相关资源
最近更新 更多