check all/uncheck all rows in datagridview with button

Harris00

Member
Joined
Feb 27, 2009
Messages
9
Programming Experience
3-5
Hello

I have data grid view with checkbox as unbound column and a button at the bottom and when button is clicked i want to check all rows in the datagrid view i.e check the checkbox if it is not checked for all rows in datagridview. If button is clicked again i want to uncheck the checkbox for all rows if the check box is checked.
I appreciate code sample please.

Regards
harris
 
It should be a simple matter of looping through each row and setting the column's value to true/false.

Here's a quick example.

VB.NET:
Public Class Form1

    Public checkUncheck As Boolean = True

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        'Fill DataTable dt here

        Me.DataGridView1.DataSource = dt
        Me.DataGridView1.Columns.Add(New DataGridViewCheckBoxColumn With {.Name = "cbc"})

    End Sub

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        SetCheckBoxColumnValues(checkUncheck)
        checkUncheck = Not checkUncheck
    End Sub

    Private Sub SetCheckBoxColumnValues(ByVal tf As Boolean)
        For Each row As DataGridViewRow In Me.DataGridView1.Rows
            row.Cells("cbc").Value = tf
        Next
    End Sub
End Class
 
Back
Top