Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Add a Checkbox Control to the DataGrid Control

0.00/5 (No votes)
14 Dec 2002 1  
Add CheckBox to ASP.NET DataGrid control (VB.NET version).

Sample Image - checkBoxGrid.jpg

Introduction

This simple demo project shows, how you can add CheckBoxes to the DataGrid web control. This article shows handling automatic selection and getting the selected CheckBoxes, too.

Select all / Deselect all items

This simple method iterates through the grid and sets the Checked state of the CheckBoxes in the grid. And sets the Button's Caption to + / -.

 Private Sub selectAll()
        Dim oDataGridItem As DataGridItem
        Dim chkExport As System.Web.UI.WebControls.CheckBox

        If cmdSelectAll.Text = "+" Then
            For Each oDataGridItem In dgMain.Items

                chkExport = oDataGridItem.FindControl("chkExport")
                chkExport.Checked = True
            Next

            cmdSelectAll.Text = "-"
        Else
            For Each oDataGridItem In dgMain.Items
                chkExport = oDataGridItem.FindControl("chkExport")
                chkExport.Checked = False
            Next
            cmdSelectAll.Text = "+"
        End If
    End Sub

Find selected Items

This method iterate through the grid items, and adds the selected rows to an array.

    Private Sub cmdFindSelected_Click(ByVal sender As _
                       System.Object, ByVal e As System.EventArgs) _
                       Handles cmdFindSelected.Click

        Dim oDataGridItem As DataGridItem
        Dim chkExport As System.Web.UI.WebControls.CheckBox
        Dim oExArgs As New System.Collections.ArrayList()
        Dim sID As String
        
        For Each oDataGridItem In dgMain.Items

            chkExport = oDataGridItem.FindControl("chkExport")
            If chkExport.Checked Then
                sID = _
                  CType(oDataGridItem.FindControl("lblColumn"), Label).Text
                oExArgs.Add(sID)
            End If
        Next

    End Sub

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here