检查DataGridViewCheckBoxCell中是否选中了复选框

时间:2012-07-04 21:02:06

标签: c# vb.net datagridview

我有DataGridView,其中包含DataGridViewColumn和按钮。当我单击按钮时,我想检查datagridview中的所有复选框是否都已选中。

我使用以下代码,但它不起作用:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    For i As Integer = 0 To DataGridView1.Rows.Count - 1
        Dim CheckBox As DataGridViewCheckBoxCell = DirectCast(DataGridView1.Rows(i).Cells(0), DataGridViewCheckBoxCell)
        If Not CheckBox.Value = Not CheckBox.Value Then
            MsgBox("True")
        End If
    Next
End Sub

2 个答案:

答案 0 :(得分:3)

我认为您的IF语句存在问题。它应该检查Value = True而不是.value = Not Checkbox,Value

If CheckBox.Value = True Then
   MsgBox("True")
End If

答案 1 :(得分:0)

我无法确定你的逻辑应该用这一行做什么:

  

如果不是CheckBox.Value = Not CheckBox.Value那么

看起来你在说,“如果没有价值=没有价值”???

试试这个:

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
  For i As Integer = 0 To DataGridView1.Rows.Count - 1
    'Dim CheckBox As DataGridViewCheckBoxCell = DirectCast(DataGridView1.Rows(i).Cells(0), DataGridViewCheckBoxCell)
    'If Not CheckBox.Value = Not CheckBox.Value Then
    '  MsgBox("True")
    'End If
    Dim obj As Object = DataGridView1.Rows(i).Cells(0)
    If (Not obj Is Nothing) Then
      Dim checkBox1 As DataGridViewCheckBoxCell = DirectCast(obj, DataGridViewCheckBoxCell)
      Dim objValue As Object = checkBox1.Value
      If (Not objValue Is Nothing) Then
        Dim checked As Boolean = DirectCast(objValue, Boolean)
        If (checked) Then
          MsgBox("True")
        End If
      End If
    End If
  Next
End Sub