You’ve seen them – a web page/a form/whatever, with checkboxes so you can enter your choices. Sometimes, you need to select all of them. Sometimes, you click the button to select all and you change your mind, so you need to start over by unselecting them all.
This code sample uses the Employees table of the Northwind database, to show you how to accomplish this in a DataGrid. To make this work on your system, just copy the code to your new page, change the provider/connection information and run it.
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SQLClient" %>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 2.2">
<title>Checkboxes in a DataGrid - Check All</title>
<script language="VB" runat="server">
Sub Page_Load(Source as Object, E as EventArgs)
Dim strConn as string = "server=YourSever;uid=YourUID;pwd=YourPWD;database=Northwind"
Dim MySQL as string = "Select FirstName, LastName, Title, HireDate from Employees"
Dim MyConn as New SQLConnection(strConn)
Dim objDR as SQLDataReader
Dim Cmd as New SQLCommand(MySQL, MyConn)
MyConn.Open()
objDR=Cmd.ExecuteReader(system.data.CommandBehavior.CloseConnection)
MyDataGrid.DataSource = objDR
MyDataGrid.DataBind()
End Sub
Sub doChecks(Source as Object, E as EventArgs)
Dim GridItem As DataGridItem
For Each griditem In MyDataGrid.Items
Dim myCheckbox As CheckBox = CType(griditem.Cells(0).Controls(1), CheckBox)
myCheckbox.Checked = True
Next
End Sub
Sub doUncheck(Source as Object, E as EventArgs)
Dim GridItem As DataGridItem
For Each griditem In MyDataGrid.Items
Dim myCheckbox As CheckBox = CType(griditem.Cells(0).Controls(1), CheckBox)
myCheckbox.Checked = False
Next
End Sub
</script>
</head>
<body>
<form runat="server" method="post">
<asp:Datagrid runat="server"
Id="MyDataGrid"
GridLines="Both"
cellpadding="0"
cellspacing="0"
Headerstyle-BackColor="#8080C0"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Size="8"
BackColor="#8080FF"
Font-Name="Arial"
Font-Size="8"
BorderColor="Black"
AutogenerateColumns="False">
<Columns>
<asp:TemplateColumn>
<ItemTemplate>
<asp:CheckBox ID="myCheckbox" Runat="server">
</asp:CheckBox>
</ItemTemplate>
</asp:TemplateColumn>
<asp:BoundColumn DataField="FirstName" HeaderText="FirstName">
</asp:BoundColumn>
<asp:BoundColumn DataField="LastName" HeaderText="LastName">
</asp:BoundColumn>
<asp:BoundColumn DataField="Title" HeaderText="Title">
</asp:BoundColumn>
<asp:BoundColumn DataField="HireDate" HeaderText="HireDate">
</asp:BoundColumn>
</Columns>
</asp:DataGrid>
<asp:Button id="btnCheck" Text="Check All" onclick="doChecks" runat="server" />
<asp:Button id="btnUnCheck" Text="Un-Check All" onclick="doUncheck" runat="server" />
</form>
</body>
</html>