Using Checkboxes in a GridView
This sample is based on the DataGrid sample with checkboxes, changing/updating the necessary items to allow it to work with a Gridview, since quite a bit of the code, etc is still the same.
<script language="VB" Runat="server">
dim ordList as String=""
Sub doSelectAll(Source as Object, E as EventArgs)
Dim dgItem As GridViewRow
Dim chkGView As System.Web.UI.WebControls.CheckBox
For Each dgItem In gvPublishers.Rows
chkGView = dgItem.FindControl("chk1")
chkGView.Checked = "True"
Next
End Sub
Sub doClearAll(Source as Object, E as EventArgs)
Dim dgItem As GridViewRow
Dim chkGView As System.Web.UI.WebControls.CheckBox
For Each dgItem In gvPublishers.Rows
chkGView = dgItem.FindControl("chk1")
chkGView.Checked = "False"
Next
label1.text=""
End Sub
Sub GetAuthorIDs(Source as Object, E as EventArgs)
Dim i As Integer
For i = 0 To gvPublishers.Rows.Count - 1
Dim dgItem As GridViewRow = gvPublishers.Rows(i)
Dim cb As CheckBox = CType(dgItem.FindControl("chk1"), CheckBox)
If Not (cb Is Nothing) And cb.Checked Then
ordList+=dgItem.Cells(2).Text & ","
else
label1.text="Nothing is checked"
End If
Next i
label1.text=KillEnding(Trim(ordList))
End Sub
Function KillEnding(sItem as String)
if sItem.Length>0 then Return sItem.Substring(0,sItem.Length-1)
End Function
</script>
<html>
<head>
<meta name="GENERATOR" Content="ASP Express 4.5">
<title>Using Checkboxes with a GridView</title>
</head>
<body>
<form id="form1" Runat="server">
<div align="center">
<asp:Label ID="label1" ForeColor="Blue" Font-Bold="True" Runat="server" />
<asp:GridView Runat="server"
Id="gvPublishers"
GridLines="Both"
cellpadding="0"
cellspacing="0"
Headerstyle-BackColor="#BDCFE7"
Headerstyle-Font-Name="Arial"
Headerstyle-Font-Size="8"
BackColor="#E7EFFF"
Font-Name="Arial"
Font-Size="8"
BorderColor="Black"
DataSourceID="SQLDS1"
AutogenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:Checkbox id="chk1" Runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="au_id" HeaderText="Author ID">
</asp:BoundField>
<asp:BoundField DataField="FullName" HeaderText="Author Name">
</asp:BoundField>
</Columns>
</asp:GridView>
<asp:Button id="btnSelectAll"
Text="Select All" onclick="doSelectAll" Runat="server" />
<asp:Button id="btnClearAll"
Text="Clear All" onclick="doClearAll" Runat="server" />
<asp:Button id="btnAuthorIDs"
Text="Get Authors" onclick="GetAuthorIDs" Runat="server" />
</div>
<asp:SQLDataSource ID="SQLDS1"
ConnectionString="<%$ ConnectionStrings:YourConnString %>"
ProviderName="System.Data.SqlClient"
SelectCommand="Select Top 10 au_id, au_fname + '' '' + au_lname as FullName from Authors" Runat="Server">
</asp:SQLDataSource>
</form>
</body>
</html>




03. Feb, 2009 








No comments yet... Be the first to leave a reply!