Display Checked Records From Gridview in ASP.Net

Introduction

This article explains how to get checked (selected) records from a GridView control. Checkboxes allow the user to select one or more rows from a gridvew control. You can access the CheckBoxes in code to determine whether a given checkbox is checked or to change the checked state.

Use the following procedure to create a sample of displaying the checked records from a GridView control.

Create DataBase and Table in SQL-SERVER

  1. Create Database Employee  
  2. use Employee  
  3. create table EmployeeInformation  
  4. (  
  5. EmpId int,  
  6. Emp_Name varchar(max),  
  7. Emp_Address nvarchar(max),  
  8. Emp_Department varchar(max)  
  9. )

Write the following procedure to insert the values in tables columns:

  1. insert into EmployeeInformation values(101,'Pankaj Lohani','A-43 Vinod New Delhi','Web Development')  
  2. insert into EmployeeInformation values(102,'Nimit Joshi','B-44 Laxminagar New Delhi','Web Development')  
  3. insert into EmployeeInformation values(103,'Pravesh Khanduri','C-45 Pratap Vihar New Delhi','Teacher')  
  4. insert into EmployeeInformation values(104,'Amit Senwal','D-46 R.K puram New Delhi','Web Development')  
  5. insert into EmployeeInformation values(105,'Ravi Kumar','E-47 Saket New Delhi','Testing')  
  6. insert into EmployeeInformation values(106,'Ainul Hasan','F-48 Saraswati Kunj New Delhi','Web Development')  
  7. insert into EmployeeInformation values(107,'Ashish','F-49 Vinod Nagar New Delhi','Software Engineer')   

Write the following query to execute the table schema:

  1. select * from EmployeeInformation

TableSchema

Step 1

Open Visual Studio then seelct "Create New Website" --> "ASP.NET Web Site".

CreateNewWebsite

Step 2

Now go to the Solution Explorer on the right side of the application and use the following procedure as in the following figure.

AddNewItem

Step 3

Add a new Web form in the empty web application as in the following figure.

AddWebForm

Step 4

Write the following code in a GridForm.aspx page:

  1. <html xmlns="http://www.w3.org/1999/xhtml">  
  2. <head>  
  3. <title></title>  
  4. </head>  
  5. <body>  
  6. <form id="form1" runat="server">  
  7. <div>  
  8. <asp:GridView ID="gvDetails" DataKeyNames="EmpId" DataSourceID="dsDetails" AutoGenerateColumns="False"   
  9. CellPadding="3" runat="server" BackColor="White" BorderColor="#999999" BorderStyle="None"   
  10. BorderWidth="1px" GridLines="Vertical">  
  11. <AlternatingRowStyle BackColor="#DCDCDC" />  
  12. <Columns>  
  13. <asp:TemplateField>  
  14. <ItemTemplate>  
  15. <asp:CheckBox ID="ChkRecords" runat="server" />  
  16. </ItemTemplate>  
  17. </asp:TemplateField>  
  18. <asp:BoundField HeaderText="EmpId" DataField="EmpId" />  
  19. <asp:BoundField HeaderText="EmpName" DataField="Emp_Name" />  
  20. <asp:BoundField HeaderText="EmpAddress" DataField="Emp_Address" />  
  21. <asp:BoundField HeaderText="EmpDept" DataField="Emp_Department" />  
  22. </Columns>  
  23.     <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />  
  24. <HeaderStyle BackColor="#000084" Font-Bold="true" ForeColor="White" />  
  25.     <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />  
  26.     <RowStyle BackColor="#EEEEEE" ForeColor="Black" />  
  27.     <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />  
  28.     <SortedAscendingCellStyle BackColor="#F1F1F1" />  
  29.     <SortedAscendingHeaderStyle BackColor="#0000A9" />  
  30.     <SortedDescendingCellStyle BackColor="#CAC9C9" />  
  31.     <SortedDescendingHeaderStyle BackColor="#000065" />  
  32. </asp:GridView>  
  33. <asp:Button ID="shwbtn" Text="Display Checked Records" runat="server"  
  34. Font-Bold="true" onclick="CheckedRecords" /><br />  
  35. <asp:Label ID="lblmsg" runat="server" />  
  36. </div>  
  37.  <asp:SqlDataSource ID="dsDetails" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection %>"  
  38.  SelectCommand="select * from EmployeeInformation">  
  39. </asp:SqlDataSource>  
  40. </form>  
  41. </body>  
  42. </html> 

A SqlDataSource control allows us to access data stored in any relational database that supports ADO.NET. It can use the "System.Data.SqlClient" provider to access  a SQL Server database. A DataSource control interacts with the DataBound controls and hides the complex data binding processes. The "SqlDataSource" represents a connection to an ADO.NET data provider that returns SQL data.

Add the ConnectionString in the Web.config file as in the following:

  1. <connectionStrings>  
  2.  <add name="dbconnection" connectionString="Data Source=; Initial Catalog=Employee;   
  3. User=abc; Password=****" providerName="SqlClient"/>  
  4. </connectionStrings>  

Design View of GetGridRows.aspx

DesignView

Step 5

Now use the following code in GetGridRows.aspx.cs:

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Data;  
  6. using System.Data.SqlClient;  
  7. using System.Web.UI;  
  8. using System.Web.UI.WebControls;  
  9. public partial class GetGridRows : System.Web.UI.Page  
  10. {  
  11.     protected void Page_Load(object sender, EventArgs e)  
  12.     {  
  13.     }  
  14.     protected void CheckedRecords(object sender, EventArgs e)  
  15.     {  
  16.         string empidstr = string.Empty;  
  17.         string empnamestr = string.Empty;  
  18.         foreach (GridViewRow gridrows in gvDetails.Rows)  
  19.         {  
  20.             CheckBox chkbox = (CheckBox)gridrows.FindControl("ChkRecords");  
  21.             if (chkbox != null & chkbox.Checked)  
  22.             {  
  23.                 empidstr += gvDetails.DataKeys[gridrows.RowIndex].Value.ToString() + ',';  
  24.                 empnamestr += gridrows.Cells[2].Text + ',';  
  25.             }  
  26.         }  
  27.         empidstr = empidstr.Trim(",".ToCharArray());  
  28.         empnamestr = empnamestr.Trim(",".ToCharArray());  
  29.         lblmsg.Text = "Employee Id: <b>" + empidstr + "</b><br/>" + "Employee Name: <b>" + empnamestr + "</b>";  
  30.     }  
  31. }   

The GridView "Rows" property provides access to the data rows in the GridView. The Rows property returns a collection of GridView instances that make up the Gridview's datarows. The "foreach" loop here enumerates this collection. For each "GridViewRow" object, the row's CheckBox is programmitically accessed using gridrows.FindControl("ChkRecords"). If the CheckBox is checked then the gridrows corresponding to the ChkRecords value is retrieved from the DataKeys collection.

Step 6

Debug the application by pressing F5 to execute the web form. After debugging the application the output will be shown in the browser as in the following figure.

AfterDebug

Step 7

Check the records that you want to display as in the following figure.

GetSingleRow

Step 8

You can check multiple records and display them as in the following figure.

GetMultipleRow

Summary

As we saw in this article, including a checkbox in a GridView entails adding a TemplateField with a checkbox web control. We can programmatically access the checkboxes in code to determine whether a given checkbox is checked or to change the checked state.


Similar Articles