Stringcollection Stringcollection Empty Gridview1 Rows Count Checkbox Checkbox Gridview1 Rows Cells Findcontrol
Stringcollection Stringcollection Empty Gridview1 Rows Count Checkbox Checkbox Gridview1 Rows Cells Findcontrol
{ CheckBox chkDelete = (CheckBox) GridView1.Rows.Cells[0].FindControl("chkSelect"); if (chkDelete != null) { if (chkDelete.Checked) { strID = GridView1.Rows.Cells[1].Text; idCollection.Add(strID); } } } for more details check this link: http://www.itworld2.com/ghowto.aspx?id=69
This article describes how you can select checkboxes inside a GridView control.
See Also
Sponsored Links
Introduction
GridView is a new data bound control introduced by Microsoft in Visual Studio .NET
2005. Most of the operations like sorting, paging and selecting items from the GridView are already built in and you can use it through the design view. In this article, I will explain how you can select single as well as all the checkboxes which are inside aGridView control.
<asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="PersonID" DataSourceID="mySource" Width="366px" CellPadding="4" ForeColor="#333333" GridLines="None"> <Columns> <asp:CommandField ShowSelectButton="True" /> <asp:BoundField DataField="PersonID" HeaderText="PersonID" InsertVisible="False" ReadOnly="True" SortExpression="PersonID" /> <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" /> <asp:TemplateField HeaderText="Select"> <ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" /> </ItemTemplate> <HeaderTemplate> </HeaderTemplate> </asp:TemplateField> </Columns> <FooterStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <RowStyle BackColor="#FFFBD6" ForeColor="#333333" /> <PagerStyle BackColor="#FFCC66" ForeColor="#333333" HorizontalAlign="Center" /> <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="Navy" /> <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="White" /> <AlternatingRowStyle BackColor="White" /> </asp:GridView>
// StringBuilder object StringBuilder str = new StringBuilder(); // Select the checkboxes from the GridView control for (int i = 0; i < GridView1.Rows.Count; i++) { GridViewRow row = GridView1.Rows[i]; bool isChecked = ((CheckBox) row.FindControl("chkSelect")).Checked; if (isChecked) { // Column 2 is the name column str.Append(GridView1.Rows[i].Cells[2].Text); } } // prints out the result Response.Write(str.ToString());
The code above just iterates through the GridView and selects the checked checkboxes. Later it appends the selected value to a StringBuilder object. In order to use StringBuilder you will need to add theSystem.Text namespace.
Collapse
<script language="javascript"> function SelectAllCheckboxes(spanChk){ // Added as ASPX uses SPAN for checkbox var oItem = spanChk.children; var theBox= (spanChk.type=="checkbox") ? spanChk : spanChk.children.item[0]; xState=theBox.checked; elm=theBox.form.elements; for(i=0;i<elm.length;i++) if(elm[i].type=="checkbox" && elm[i].id!=theBox.id) { //elm[i].click(); if(elm[i].checked!=xState) elm[i].click(); //elm[i].checked=xState; } } </script>
In this example i am going to describe how to implement CheckAll CheckBox in GridView to check all the rows in gridView. For this i have put a checkBox in header Template of gridview which on checking will check all the rows in gridview usingserver side code.
<asp:GridView ID="GridView1" runat="server" DataSourceID="SqlDataSource1" AutoGenerateColumns="false" CellPadding="2" ForeColor="#333333" GridLines="Both" DataKeyNames="ID" OnRowDataBound="GridView1_RowDataBound"> <Columns> <asp:TemplateField HeaderText="CheckAll"> <HeaderTemplate> <asp:CheckBox ID="chkSelectAll" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelectAll_CheckedChanged"/> </HeaderTemplate> <ItemTemplate> <asp:CheckBox ID="chkSelect" runat="server" AutoPostBack="true" OnCheckedChanged="chkSelect_CheckedChanged"/> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="ID" HeaderText="ID" SortExpression="ID"/> <asp:TemplateField HeaderText="Name" SortExpression="Name"> <ItemTemplate> <asp:TextBox ID="txtName" runat="server" Text='<%# Bind("Name") %>' ForeColor="Blue" BorderStyle="none" BorderWidth="0px" ReadOnly="true" > </asp:TextBox> </ItemTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Location" SortExpression
="Location"> <ItemTemplate> <asp:TextBox ID="txtLocation" runat="server" Text='<%# Bind("Location") %>' ForeColor="Blue" BorderStyle="none" ReadOnly="true"> </asp:TextBox> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:ConnectionString %>" SelectCommand="SELECT [ID], [Name], [Location] FROM [Details]" DeleteCommand="DELETE FROM Details WHERE (ID = @ID)" UpdateCommand="UPDATE [Details] SET [Name] = @Name, [Location] = @Location WHERE [ID] = @ID"> <DeleteParameters> <asp:Parameter Name="ID" /> </DeleteParameters> <UpdateParameters> <asp:Parameter Name="Name" /> <asp:Parameter Name="Location" /> <asp:Parameter Name="ID" /> </UpdateParameters> </asp:SqlDataSource> <asp:Button ID="btnUpdate" runat="server" OnClick="btnUpdate_Click" Text="Update" /> <asp:Button ID="btnDelete" runat="server" OnClick="btnDelete_Click" Text="Delete" />
C# Code behind 01protected void chkSelectAll_CheckedChanged 02 03{ 04 CheckBox chkAll = 05 (CheckBox)GridView1.HeaderRow.FindControl("chkSelectAll"); (object sender, EventArgs e)
12 13 14 15 16 17 18 19 20 } }
chkSel.Checked = true; TextBox txtname = (TextBox)gvRow.FindControl("txtName"); TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation"); txtname.ReadOnly = false; txtlocation.ReadOnly = false; txtname.ForeColor = System.Drawing.Color.Black; txtlocation.ForeColor = System.Drawing.Color.Black;
21 else 22 { 23 24 25 26 27 28 29 30 31 32 33 34 35} } foreach (GridViewRow gvRow in GridView1.Rows) { CheckBox chkSel = (CheckBox)gvRow.FindControl("chkSelect"); chkSel.Checked = false; TextBox txtname = (TextBox)gvRow.FindControl("txtName"); TextBox txtlocation = (TextBox)gvRow.FindControl("txtLocation"); txtname.ReadOnly = true; txtlocation.ReadOnly = true; txtname.ForeColor = System.Drawing.Color.Blue; txtlocation.ForeColor = System.Drawing.Color.Blue; }
VB.NET code behind 01Protected Sub chkSelectAll_CheckedChanged(ByVal sender As Object, ByVal e As EventArgs) 02 03 04 05 06 07 08 09 10 Dim chkAll As CheckBox = DirectCast(GridView1.HeaderRow.FindControl("chkSelectAll"), CheckBox) If chkAll.Checked = True Then For Each gvRow As GridViewRow In GridView1.Rows Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox) chkSel.Checked = True Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox) Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox) txtname.[ReadOnly] = False txtlocation.[ReadOnly] = False
For Each gvRow As GridViewRow In GridView1.Rows Dim chkSel As CheckBox = DirectCast(gvRow.FindControl("chkSelect"), CheckBox) chkSel.Checked = False Dim txtname As TextBox = DirectCast(gvRow.FindControl("txtName"), TextBox) Dim txtlocation As TextBox = DirectCast(gvRow.FindControl("txtLocation"), TextBox) txtname.[ReadOnly] = True txtlocation.[ReadOnly] = True txtname.ForeColor = System.Drawing.Color.Blue txtlocation.ForeColor = System.Drawing.Color.Blue
26End Sub
ber 2010 I updated the code and concepts presented in this article to use unobtrusive JavaScript and the jQuery library. To learn m king All Checkboxes in a GridView Using jQuery.
Introduction
A common website user interface pattern is a list of items with a checkbox in each row. The archetypical example is the web-based email client, which allows a series of messages to be selected by checking that email's checkbox. Once one or more emails have been selected, the user can apply some group action on those selected messages, such as deleting them, marking them read, or moving them to a different folder. In addition to having the ability to check each record, one at a time, many such user interfaces also provide a "check all" checkbox in the header row. This checkbox, if checked or unchecked, automatically checks or unchecks all items in the list below. Creating such a user interface with ASP.NET 2.0's GridView control is quite possible, and is the focus of this article. In particular, we'll look at how to enable "Check All"/"Uncheck All" functionality both using server-side code and client-side script. The server-side option is much simpler to implement, but suffers from requiring a postback when opting to check or uncheck all checkboxes. The client-side approach, on the other hand, offers a snappier and sleeker user interface, but does require a bit more effort to implement correctly.
- continued -
Before we examine how, exactly, to provide functionality to check or uncheck each checkbox in a GridView, let's first concentrate on building a GridView control that possesses a CheckBox for each row. A column of CheckBoxes can be added to the GridView using one of two approaches:
Using the CheckBoxField - the CheckBoxField is a built-in GridView field type that renders a column of CheckBoxes with each CheckBox's Checked property assigned to some data field in the grid's underlying data source. Using a TemplateField - we can add a TemplateField and then, in the CheckBox Web control. If the CheckBox Web control's underlying data field value, the as,
Checked property can be set either declaratively (such <asp:CheckBox runat="server" ... Checked='<%# Eval("ColumnName") %>' ... />) or programmatically (such as in the RowDataBound event handler).
The second option - using a TemplateField - has a number of advantages. First, it's more customizable. With minimal effort we can include additional markup in each row and can provide a custom header, even. In fact, the code download at the end of this article includes an example with a CheckBox in this column's header, which the user can check or uncheck all CheckBoxes in the GridView; for more information see Checking All CheckBoxes in a GridView Using Client-Side Script and a Check All CheckBox. Moreover, if the CheckBox's Checkedproperty is not dependent on some underlying data field, then you'll need to use the TemplateField option. In this article we will use the TemplateField option. For this article, imagine that we wanted to build some web-based file management tool. In particular, this interface will list the files in the current directory, along with a CheckBox for each file. After the GridView, we'll add a "Delete All Checked Files" Button that, when clicked, will delete those files from the file system whose CheckBox has been checked. (The live demo available at the end of this article doesn't actually delete the files; rather, it just prints a message indicating what files it would have deleted, had that functionality been implemented.) The following GridView accomplished the needed functionality. Note that it uses a TemplateField to house a CheckBox control for each GridView row. (Some of the GridView's formatting-related settings have been removed for brevity.)
<asp:GridView ID="FileList" runat="server" AutoGenerateColumns="False" DataKeyNames="FullName"> <Columns> <asp:TemplateField> <ItemTemplate> <asp:CheckBox runat="server" ID="RowLevelCheckBox" /> </ItemTemplate> </asp:TemplateField> <asp:BoundField DataField="Name" HeaderText="Name" /> <asp:BoundField DataField="CreationTime" HeaderText="Created On"> <ItemStyle HorizontalAlign="Right" /> </asp:BoundField> <asp:BoundField DataField="Length" DataFormatString="{0:N0}" HeaderText="File Size" HtmlEncode="False"> <ItemStyle HorizontalAlign="Right" /> </asp:BoundField> </Columns> </asp:GridView>
The files in the current directory are accessed and bound to the GridView in the using the following code:
Protected Sub Page_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Dim dirInfo As New DirectoryInfo(Request.PhysicalApplicationPath) FileList.DataSource = dirInfo.GetFiles() FileList.DataBind() End If End Sub
For more information on accessing and displaying the files in a directory, see Displaying the Files in a Directory Using a DataGrid...
Next, we need a "Delete All Checked Files" Button that, when clicked, determines what CheckBoxes have been checked and deletes those files. The following Click event handler for that Button iterates through the
Rows collection and, for each GridViewRow instance, determines whether or not the RowLevelCheckBox has been checked. If it has, the event handler concatenates the file path to a Label Web control (Summary). (In practice, it would use the File.Delete(path) method in the System.IO namespace to actually delete the file.)
GridView's CheckBox
Protected Sub DeleteButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles DeleteButton.Click Summary.Text = "The following file would have been deleted:<ul>" Dim currentRowsFilePath As String 'Enumerate the GridViewRows For index As Integer = 0 To FileList.Rows.Count - 1 'Programmatically access the CheckBox from the TemplateField Dim cb As CheckBox = CType(FileList.Rows(index).FindControl("RowLevelCheckBox"), CheckBox) 'If it's checked, delete it... If cb.Checked Then currentRowsFilePath = FileList.DataKeys(index).Value Summary.Text &= String.Concat("<li>", currentRowsFilePath, "</li>") End If Next Summary.Text &= "</ul>" End Sub
Note how the CheckBox is programmatically referenced from the TemplateField FileList.Rows(index).FindControl("controlID"). Had we used a CheckBoxField, the syntax would have instead been
have accessed the first column in the specified row (this assumes that the CheckBoxField was the first field in the GridView) and Control(0) references that column's first control in its Controls collection, which, for the CheckBoxField, is its CheckBox control. Now that we have the groundwork laid out, we're ready to examine how to implement functionality to check and uncheck all CheckBoxes in the GridView. Let's first look at how to provide this functionality using serverside code.
Providing "Check All" and "Uncheck All" Functionality Using Server-Side Code
To provide "Check All" and "Uncheck All" functionality I added to Button Web controls above the GridView:
<p> <asp:Button ID="CheckAll" runat="server" Text="Check All" /> <asp:Button ID="UncheckAll" runat="server" Text="Uncheck All" /> </p> Click event handlers for both of these Buttons, in which I enumerate the Rows collection and, for each GridViewRow instance, access the CheckBox and set itsChecked property accordingly:
Next, I created GridView's
'Enumerate each GridViewRow For Each gvr As GridViewRow In FileList.Rows 'Programmatically access the CheckBox from the TemplateField Dim cb As CheckBox = CType(gvr.FindControl("RowLevelCheckBox"), CheckBox) 'Check it! cb.Checked = True Next End Sub Protected Sub UncheckAll_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles UncheckAll.Click 'Enumerate each GridViewRow For Each gvr As GridViewRow In FileList.Rows 'Programmatically access the CheckBox from the TemplateField Dim cb As CheckBox = CType(gvr.FindControl("RowLevelCheckBox"), CheckBox) 'Uncheck it! cb.Checked = False Next End Sub
That's all there is to it! The only issue with the server-side approach is that clicking the "Check All" or "Uncheck All" checkboxes results in a postback, which adds overhead, a screen flash, and so on. While such behavior may be unnoticeable in an intranet scenario, Internet sites typically strive to provide a better user experience through the use of client-side script. Such functionality can be achieved, but requires a bit more effort. Before we turn our attention to the client-side scripting functionality, take a moment to check out the screen shot of the server-side approach in action. Note that clicking the "Check All" or "Uncheck All" Buttons will appropriately check or uncheck all of the CheckBoxes in the GridView; the following screen shot shows the grid right after the "Check All" Button has been clicked.
Providing "Check All" and "Uncheck All" Functionality with Client-Side Script
In order to provide a snappier user experience, ideally the "Check All" and "Uncheck All" would check or uncheck all of the CheckBoxes on the client-side without causing a postback. The CheckBoxes in the GridView can be accessed through client-side JavaScript using the following pattern:
// Get a reference to the CheckBox var cb = document.getElementById('checkBoxID'); // Adjust the checked state cb.Checked = false; // or whatever...
Here, checkBoxID is the client-side ID of the rendered CheckBox control. This is not necessarily the same as the value of the ID property of the CheckBox Web control. Instead, the client-side ID is prepended with the script we need to create a client-side
IDs of the CheckBox Web control's parent controls. In order to work with the CheckBoxes in client-side Array of the client-side IDs of the GridView CheckBoxes. ClientScriptManager class, which can be accessed ClientScript property. This class has the same client-script-
ASP.NET 2.0 provides a number of methods in the directly from an ASP.NET page using the related methods found in the
Page class in ASP.NET 1.x, along with some additional methods. One such arrayValue), which creates a client-side Array with elements specified by the arrayValue input parameter. (To add multiple elements to a single array, call RegisterArrayDeclaration(arrayName, arrayValue) multiple
method (available both in 1.x and 2.0) isRegisterArrayDeclaration(arrayName, times, passing in the same arrayName value.) The following code enumerates the GridView's in a client-side
programmatically accesses the CheckBox and stores its client-side ID (accessible via theClientID property)
Array (ClientSideIDs).
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Dim dirInfo As New DirectoryInfo(Request.PhysicalApplicationPath) FileList.DataSource = dirInfo.GetFiles() FileList.DataBind() End If 'On every page visit we need to build up the CheckBoxIDs array For Each gvr As GridViewRow In FileList.Rows 'Get a programmatic reference to the CheckBox control Dim cb As CheckBox = CType(gvr.FindControl("RowLevelCheckBox"), CheckBox) ClientScript.RegisterArrayDeclaration("CheckBoxIDs", String.Concat("'", cb.ClientID, "'")) Next End Sub
This code will add JavaScript to the page that looks similar to the following:
// --> </script>
This code needs to be placed in the
these types of client-side injected arrays are not persisted across postbacks. If we only create this clientside Array on the first page visit (or whenever the GridView is data bound), upon postback - such as when clicking the "Delete All Checked Files" Button Web control - the subsequent page load will not include the CheckBoxIDs client-side Array, thereby rendering the "Check All" and "Uncheck All" functionality impotent. For more information on working with client-side script from server-side code, be sure to read Working With Client-Side Script... Armed with this array of client-side IDs, we can write a client-side JavaScript function that enumerates this array's elements and, for each element, references the checkbox and sets itschecked property accordingly. I've created two functions to accomplish this:
ChangeCheckBoxState(id, checkState) - references the specified checkbox (using document.getElementById(id)) and sets its checked property to the value
of checkedState
ChangeAllCheckBoxStates(checkState) - iterates through the CheckBoxIDs array and, for each element, calls ChangeCheckBoxState, passing in the client-side ID value for the currentCheckBoxIDs element along with the checkState value <input type="button" ... /> buttons - "Check All" and "Uncheck All" - and onclick event such that it invoked ChangeAllCheckBoxStates, passing in
<script type="text/javascript"> function ChangeCheckBoxState(id, checkState) { var cb = document.getElementById(id); if (cb != null) cb.checked = checkState; } function ChangeAllCheckBoxStates(checkState) { // Toggles through all of the checkboxes defined in the CheckBoxIDs array // and updates their value to the checkState input parameter if (CheckBoxIDs != null) { for (var i = 0; i < CheckBoxIDs.length; i++) ChangeCheckBoxState(CheckBoxIDs[i], checkState); } } </script> ... <p> <input type="button" value="Check All" onclick="ChangeAllCheckBoxStates(true);" /> <input type="button" value="Uncheck All" onclick="ChangeAllCheckBoxStates(false);" /> </p>
With these changes added, the "Check All" and "Uncheck All" buttons perform their task completely on the client-side, thereby providing a snappier user experience. The download available at the end of this article includes an additional example that illustrates how to augment the client-side example to include a checkbox in the header of the column of checkboxes that, if checked or unchecked, checks or unchecks all of the checkboxes in the grid. A more thorough examination of this extra example can be found at Checking All CheckBoxes in a GridView Using Client-Side Script and a Check All CheckBox!
Conclusion
In this article we examined two ways to check (or uncheck) all CheckBoxes within a GridView control. This can be accomplished most easily using server-side code, but at the expense of a postback. A client-side approach offers a snappier user experience, but requires a bit more code and some JavaScript functions as well. Happy Programming! By Scott Mitchell
checkbox in gridview
Posted 11 May 2007 - 10:32 AM
hi, i'm new to asp.net and i want some help.I am trying to create an asp.net page with c#.it has a gridview which will be populated with item from the DB when the page is loaded. I want to add a checkbox column and after teh user checks on one item, on the click of a button he should be able to purchse it. That is, after the button is clicked i should be able to load that selected item into my DB table. can anyone please help. I tried to add the checkbox field but i dont know how to go ahead. Please help!
#10JellyBean
MultiQuote
Quote + Reply
D.I.C Head
Reputation: 6
Posts:60 Joined:25-April 07
You need to define a checkbox column as a TemplateField. Below is an example showing how to retrieve the key of each checked item. CheckBoxExample.aspx
<%@ Page 0 Language="C#" AutoEventWireup="true"CodeFile="CheckBoxExample.aspx.cs" Inh 1 erits="CheckBoxExample" %> 0 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 03 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd">
<asp:GridView 1 ID="ProductGridView" runat="server"AutoGenerateColumns="False" DataKeyName 2 s="ItemId"> 13 14 <Columns> <asp:BoundField DataField="ItemDescription"DataFormatString="{0}" HeaderText="Item" /> <asp:BoundField DataField="ItemPrice" DataFormatString="{0:C}" HeaderText="Price" /> <asp:TemplateField HeaderText="Purchase"> <ItemTemplate> <asp:CheckBox ID="CheckBoxPurchase" runat="server"Enabled="true" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:Button ID="Purchase" runat="server" Text="Purchase Checked Items" /> </div> </form>
15 16 17 18 19 20 21 22
23 24 25
26 </body> 27 </html>
CheckBoxExample.aspx.cs
01 using System; 02 using System.Data; 03 using System.Configuration; 04 using System.Collections.Generic; 05 using System.Web; 06 using System.Web.Security; 07 using System.Web.UI; 08 using System.Web.UI.WebControls; 09 using System.Web.UI.WebControls.WebParts; 10 using System.Web.UI.HtmlControls; 11 12 public partial class CheckBoxExample : System.Web.UI.Page 13 { 14 15 16 17 18 19 20 21 protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // Set up the datagrid DataTable productData = CreateData(); ProductGridView.DataSource = productData; ProductGridView.DataBind();
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 }
} else { // Are there checked boxes? List<int> purchaseProductList = new List<int>(); for (int i = 0; i < ProductGridView.Rows.Count; i++) { int productId = (int)ProductGridView.DataKeys[i][0]; CheckBox cb = (CheckBox)ProductGridView.Rows[i].FindControl("CheckBoxPurchase"); if (cb.Checked) { purchaseProductList.Add(productId); } } // Do something with purchaseProductList }
private DataTable CreateData() { DataTable t = new DataTable(); t.Columns.Add(new DataColumn("ItemId", typeof(int))); t.Columns.Add(new DataColumn("ItemDescription", typeof(string))); t.Columns.Add(new DataColumn("ItemPrice", typeof(decimal)));
46 47 48 49 50 51 52 53 54 55 56 57 58 } }
DataRow r = t.NewRow(); r["ItemId"] = 1; r["ItemDescription"] = "Diamond Bling Grill"; r["ItemPrice"] = 19.99; t.Rows.Add(r); r = t.NewRow(); r["ItemId"] = 2; r["ItemDescription"] = "Silver Toaster"; r["ItemPrice"] = 9.99; t.Rows.Add(r); return t;
#14foramit1581
MultiQuote
Quote + Reply
New D.I.C Head
Reputation: 2
Posts:1 Joined:24-August 07
HI, Thanks for this article....but i m getting an error while selecting DATAKEYS...It saying that "Index out of range......should be non negative..." what should I do??? Amit
Below is an example showing how to retrieve the key of each checked item.
CheckBoxExample.aspx
<%@ Page 0 Language="C#" AutoEventWireup="true" CodeFile="CheckBoxExample.aspx.cs"Inh 1 erits="CheckBoxExample" %> 0 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 03 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd"> 04 05 <html xmlns="http://www.w3.org/1999/xhtml" > 06 <head runat="server"> 07 <title>CheckBox Example</title>
14
<asp:BoundField DataField="ItemDescription" DataFormatString="{0}"HeaderText="Item" /> <asp:BoundField DataField="ItemPrice" DataFormatString="{0:C}" HeaderText="Price"/> <asp:TemplateField HeaderText="Purchase"> <ItemTemplate> <asp:CheckBox ID="CheckBoxPurchase" runat="server" Enabled="true" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> <asp:Button ID="Purchase" runat="server" Text="Purchase Checked Items" /> </div> </form>
15 16 17 18
19 20 21 22
23 24 25
26 </body> 27 </html>
CheckBoxExample.aspx.cs
01 using System; 02 using System.Data; 03 using System.Configuration; 04 using System.Collections.Generic; 05 using System.Web; 06 using System.Web.Security; 07 using System.Web.UI;
08 using System.Web.UI.WebControls; 09 using System.Web.UI.WebControls.WebParts; 10 using System.Web.UI.HtmlControls; 11 12 public partial class CheckBoxExample : System.Web.UI.Page 13 { 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 } else { // Are there checked boxes? List<int> purchaseProductList = new List<int>(); for (int i = 0; i < ProductGridView.Rows.Count; i++) { int productId = (int)ProductGridView.DataKeys[i][0]; CheckBox cb = (CheckBox)ProductGridView.Rows[i].FindControl("CheckBoxPurchase"); if (cb.Checked) { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { // Set up the datagrid DataTable productData = CreateData(); ProductGridView.DataSource = productData; ProductGridView.DataBind();
31 32
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 } } } } }
purchaseProductList.Add(productId);
private DataTable CreateData() { DataTable t = new DataTable(); t.Columns.Add(new DataColumn("ItemId", typeof(int))); t.Columns.Add(new DataColumn("ItemDescription", typeof(string))); t.Columns.Add(new DataColumn("ItemPrice", typeof(decimal))); DataRow r = t.NewRow(); r["ItemId"] = 1; r["ItemDescription"] = "Diamond Bling Grill"; r["ItemPrice"] = 19.99; t.Rows.Add(r); r = t.NewRow(); r["ItemId"] = 2; r["ItemDescription"] = "Silver Toaster"; r["ItemPrice"] = 9.99; t.Rows.Add(r); return t;
58 }
ASP.Net GridView Checkbox value can be accessed using the same method that we discussed in the previous tutorial of ASP.Net GridView FindControl Checkbox. FindControl function returns the server control object as a naming container of server control. This same FindControlfunction can be used to access the server controls and their values placed inside the ASP.Net GridView Columns. The only difference is control type casting is required to access the relevant properties associates with any particular ASP.Net server control. For exampleChecked property value of checkbox that we will discuss in this tutorial. You can access the current state value of checkbox placed inside the ASP.Net GridView control using FindControl function.GridViewRow Class enables you to access the instance of a particular row and its Cells (Columns). You can access any particular cell by passing the number value such as 0, 1 or 2 to access 1st, 2nd or 3rd column within the limit of number of columns in each row. If there are 3 columns in each row of GridView then you can access each cell by passing 0 for 1st column, 1 for 2nd column and 2 for 3rd column.
GridView Examples:
You can see the live samples and examples of GridView from the following links:
Checkbox Value FindControl Checkbox Checkbox Column Select All Checkbox JavaScript Validation Maintain Checkbox State while Paging
// chk.checked will access the checkbox state value (on button click event) if (chk.Checked) { Response.Write( GridView1.DataKeys[rowItem.RowIndex ]["CategoryID"].ToString() + "<br />"); } }
Above C# code shows how to find checkbox control placed inside theASP.Net GridView column and access its checked property value by type casting the control object returned by the FindControl function. You can also access the other database values for that particular row having checkbox checked state equal to true. In the above example code GridView DataKeys collection has been used to access the "categoryID" value representing the unique value for each GridView row items. If condition has been used here to test the value of checked property of checkbox in each row of GridView and shows the "categoryID" as output result on the web page for which it returns true. Note: Categories table of SQL Northwind database has been used in the sample code to bind the data with GridView control. Output: Get the output of above discussed code from the following link: GridView Checkbox Value
ASP.Net GridView FindControl function can be used to access theCheckbox control placed inside the ItemTemplate of TemplateField Column. FindControl function returns the naming container of the server control (e.g. checkbox in this tutorial) whos ID is passed to the function. ASP.Net GridView FindControl function searches the server control within the row items and column of the GridView control. In this tutorial we will discuss how to find checkbox control placed inside the ASP.Net GridView also you can access the properties of checkbox control such as Text property or checkbox state property i.e. Checked.
GridView Examples:
You can see the live samples and examples of GridView from the following links:
FindControl Checkbox Checkbox Column Checkbox Column Select All Checkbox JavaScript Validation Maintain Checkbox State while Paging
// chk.checked will access the checkbox state on button click event if (chk.Checked) { Response.Write(chk.ClientID + "<br />"); } }
Above C# code shows the use of ASP.Net GridView FindControl Checkbox to access the Checked property of checkbox placed inside the GridView control. C# foreach loop has been used to access the checkbox inside each row of the GridView control. rowItem object ofGridViewRow Class enables you to access the instance of a particular row and its Cells (Columns). You can access any particular cell by passing the number value such as 0, 1 or 2 to access 1st, 2nd or 3rd column within the limit of number of columns in each row. If there are 3 columns in each row of GridView then you can access each cell by passing 0 for 1st column, 1 for 2nd column and 2 for 3rd column. In the given sample code you can see that we have placed a checkbox control inside the first column of GridView control that is why we have usedrowItem.Cells[0].FindControl( "chk1" ) to access the 1st cell of each row. "chk1" is passed as string id parameter of FindControl function to access the checkbox control by ID. Output: Get the output of above discussed code from the following link: GridView FindControl Checkbox Continue reading to the next tutorial ASP.Net GridView Checkbox Select All using C# to learn how to select all the checkbox controls placed inside the GridView control with a single click.
>>
Sometimes we need to have checkboxes in the GridView control and we want that as soon as the Checkbox is clicked/checked the postback happens and we get the value from the first row in the GridView control. This can be easily done by using the following code: <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnRowCommand="GridView1_RowCommand"> <Columns> <asp:BoundField DataField="CategoryID" HeaderText="CategoryID" /> <asp:BoundField DataField="CategoryName" HeaderText="CategoryName" /> <asp:TemplateField HeaderText="Select"> <ItemTemplate> <asp:CheckBox ID="CheckBox1" AutoPostBack="true" runat="server" OnCheckedChanged="CheckBox1_CheckedChanged1" /> </ItemTemplate> </asp:TemplateField> </Columns> </asp:GridView> And the code behind: protected void CheckBox1_CheckedChanged1(object sender, EventArgs e) { CheckBox checkbox = (CheckBox)sender; GridViewRow row = (GridViewRow) checkbox.NamingContainer; Response.Write(row.Cells[0].Text); } Ohh by the way when you click a different checkbox it will show you the new value but does not clear the old checkbox. You can make a simple method "ClearCheckboxSelection" which clears all the checkboxes. Hope you find this example useful :)