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
- Create Database Employee
- use Employee
- create table EmployeeInformation
- (
- EmpId int,
- Emp_Name varchar(max),
- Emp_Address nvarchar(max),
- Emp_Department varchar(max)
- )
Write the following procedure to insert the values in tables columns:
- insert into EmployeeInformation values(101,'Pankaj Lohani','A-43 Vinod New Delhi','Web Development')
- insert into EmployeeInformation values(102,'Nimit Joshi','B-44 Laxminagar New Delhi','Web Development')
- insert into EmployeeInformation values(103,'Pravesh Khanduri','C-45 Pratap Vihar New Delhi','Teacher')
- insert into EmployeeInformation values(104,'Amit Senwal','D-46 R.K puram New Delhi','Web Development')
- insert into EmployeeInformation values(105,'Ravi Kumar','E-47 Saket New Delhi','Testing')
- insert into EmployeeInformation values(106,'Ainul Hasan','F-48 Saraswati Kunj New Delhi','Web Development')
- insert into EmployeeInformation values(107,'Ashish','F-49 Vinod Nagar New Delhi','Software Engineer')
Write the following query to execute the table schema:
- select * from EmployeeInformation
Step 1
Open Visual Studio then seelct "Create New Website" --> "ASP.NET Web Site".
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.
Step 3
Add a new Web form in the empty web application as in the following figure.
Step 4
Write the following code in a GridForm.aspx page:
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <title></title>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <asp:GridView ID="gvDetails" DataKeyNames="EmpId" DataSourceID="dsDetails" AutoGenerateColumns="False"
- CellPadding="3" runat="server" BackColor="White" BorderColor="#999999" BorderStyle="None"
- BorderWidth="1px" GridLines="Vertical">
- <AlternatingRowStyle BackColor="#DCDCDC" />
- <Columns>
- <asp:TemplateField>
- <ItemTemplate>
- <asp:CheckBox ID="ChkRecords" runat="server" />
- </ItemTemplate>
- </asp:TemplateField>
- <asp:BoundField HeaderText="EmpId" DataField="EmpId" />
- <asp:BoundField HeaderText="EmpName" DataField="Emp_Name" />
- <asp:BoundField HeaderText="EmpAddress" DataField="Emp_Address" />
- <asp:BoundField HeaderText="EmpDept" DataField="Emp_Department" />
- </Columns>
- <FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
- <HeaderStyle BackColor="#000084" Font-Bold="true" ForeColor="White" />
- <PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
- <RowStyle BackColor="#EEEEEE" ForeColor="Black" />
- <SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
- <SortedAscendingCellStyle BackColor="#F1F1F1" />
- <SortedAscendingHeaderStyle BackColor="#0000A9" />
- <SortedDescendingCellStyle BackColor="#CAC9C9" />
- <SortedDescendingHeaderStyle BackColor="#000065" />
- </asp:GridView>
- <asp:Button ID="shwbtn" Text="Display Checked Records" runat="server"
- Font-Bold="true" onclick="CheckedRecords" /><br />
- <asp:Label ID="lblmsg" runat="server" />
- </div>
- <asp:SqlDataSource ID="dsDetails" runat="server" ConnectionString="<%$ConnectionStrings:dbconnection %>"
- SelectCommand="select * from EmployeeInformation">
- </asp:SqlDataSource>
- </form>
- </body>
- </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:
- <connectionStrings>
- <add name="dbconnection" connectionString="Data Source=; Initial Catalog=Employee;
- User=abc; Password=****" providerName="SqlClient"/>
- </connectionStrings>
Design View of GetGridRows.aspx
Step 5
Now use the following code in GetGridRows.aspx.cs:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Data;
- using System.Data.SqlClient;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- public partial class GetGridRows : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- }
- protected void CheckedRecords(object sender, EventArgs e)
- {
- string empidstr = string.Empty;
- string empnamestr = string.Empty;
- foreach (GridViewRow gridrows in gvDetails.Rows)
- {
- CheckBox chkbox = (CheckBox)gridrows.FindControl("ChkRecords");
- if (chkbox != null & chkbox.Checked)
- {
- empidstr += gvDetails.DataKeys[gridrows.RowIndex].Value.ToString() + ',';
- empnamestr += gridrows.Cells[2].Text + ',';
- }
- }
- empidstr = empidstr.Trim(",".ToCharArray());
- empnamestr = empnamestr.Trim(",".ToCharArray());
- lblmsg.Text = "Employee Id: <b>" + empidstr + "</b><br/>" + "Employee Name: <b>" + empnamestr + "</b>";
- }
- }
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.
Step 7
Check the records that you want to display as in the following figure.
Step 8
You can check multiple records and display them as in the following figure.
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.