Retrieve Rows Selected Using CheckBox in an ASP.NET GridView

I bet you must have seen this question asked a several times ‘How Can I find out which Checkboxes were selected in a GridView. I also want to retrieve row data for these selected rows on Postback’.

I personally have seen this question hundreds of times on the forums, newsgroups. If you have been facing this requirement, here’s a full working example for you to try out. This example binds the GridView to a List<>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<
html xmlns="http://www.w3.org/1999/xhtml">
<
head runat="server">
<
title>Get Selected Rows during PostBack</title>
</
head>
<
body>
<
form id="form1" runat="server">
<
div>
<
asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false"
DataKeyNames="ID" >
<
Columns>
<
asp:TemplateField>
<
ItemTemplate>
<
asp:CheckBox ID="chkSel" runat="server" />
</
ItemTemplate>
</
asp:TemplateField>
<
asp:BoundField DataField="ID" HeaderText="EmployeeId"
SortExpression="EmployeeId" />
<
asp:BoundField DataField="FName" HeaderText="FirstName"
SortExpression="FirstName" />
<
asp:BoundField DataField="Age" HeaderText="Age"
SortExpression="Age" />
<
asp:BoundField DataField="Sex" HeaderText="Sex"
SortExpression="Sex" />
</
Columns>
</
asp:GridView>
<
br />
<
asp:Button ID="btnRetrieveCheck" runat="server"
Text="Retrieve Checked Items" onclick="btnRetrieveCheck_Click" />
</
div>
</
form>
</
body>
</
html>



Points to observe:

- The AutoGenerateColumns of the GridView is set to false

- The CheckBox has been added inside an ItemTemplate

- DataKeyName of the GridView is set to ID.

C#

using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default4 : System.Web.UI.Page
{
List<Employee> listEmp = new List<Employee>();

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Employee emp = new Employee();
listEmp = emp.GetEmployees();
this.GridView1.DataSource = listEmp;
this.GridView1.DataBind();
}
}

protected void btnRetrieveCheck_Click(object sender, EventArgs e)
{
foreach (GridViewRow row in GridView1.Rows)
{
CheckBox cb = (CheckBox)row.FindControl("chkSel");
if (cb != null && cb.Checked)
{
Response.Write("Employee Id: " +
GridView1.DataKeys[row.RowIndex].Value
+ " Name: " + row.Cells[2].Text + "<br/>");
}
}
}
}

public class Employee
{

public int ID { get; set; }

public string FName { get; set; }

public int Age { get; set; }

public char Sex { get; set; }

public List<Employee> GetEmployees()
{
List<Employee> eList = new List<Employee>();

eList.Add(new Employee() { ID = 1, FName = "John", Age = 23, Sex = 'M' });

eList.Add(new Employee() { ID = 2, FName = "Mary", Age = 25, Sex = 'F' });

eList.Add(new Employee() { ID = 3, FName = "Amber", Age = 23, Sex = 'M' });

eList.Add(new Employee() { ID = 4, FName = "Kathy", Age = 25, Sex = 'M' });

eList.Add(new Employee() { ID = 5, FName = "Lena", Age = 27, Sex = 'F' });

eList.Add(new Employee() { ID = 6, FName = "John", Age = 28, Sex = 'M' });

eList.Add(new Employee() { ID = 7, FName = "Kathy", Age = 27, Sex = 'F' });

eList.Add(new Employee() { ID = 8, FName = "John", Age = 28, Sex = 'M' });

return eList;
}


}

VB.NET

Imports System
Imports System.Collections.Generic
Imports System.Web.UI
Imports System.Web.UI.WebControls

Partial Public Class Default4
Inherits System.Web.UI.Page
Private listEmp As New List(Of Employee)()

Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
If (Not Page.IsPostBack) Then
Dim
emp As New Employee()
listEmp = emp.GetEmployees()
Me.GridView1.DataSource = listEmp
Me.GridView1.DataBind()
End If
End Sub

Protected Sub
btnRetrieveCheck_Click(ByVal sender As Object, _
ByVal e As EventArgs)
For Each row As GridViewRow In GridView1.Rows
Dim cb As CheckBox = CType(row.FindControl("chkSel"), CheckBox)
If cb IsNot Nothing AndAlso cb.Checked Then
Response.Write("Employee Id: " & _
GridView1.DataKeys(row.RowIndex).Value & " Name: " & _
row.Cells(2).Text & "<br/>")
End If
Next
row
End Sub
End Class
Public Class Employee

Private privateID As Integer
Public Property
ID() As Integer
Get
Return
privateID
End Get
Set
(ByVal value As Integer)
privateID = value
End Set
End Property

Private
privateFName As String
Public Property
FName() As String
Get
Return
privateFName
End Get
Set
(ByVal value As String)
privateFName = value
End Set
End Property

Private
privateAge As Integer
Public Property
Age() As Integer
Get
Return
privateAge
End Get
Set
(ByVal value As Integer)
privateAge = value
End Set
End Property

Private
privateSex As Char
Public Property
Sex() As Char
Get
Return
privateSex
End Get
Set
(ByVal value As Char)
privateSex = value
End Set
End Property

Public Function
GetEmployees() As List(Of Employee)
Dim eList As New List(Of Employee)()

eList.Add(New Employee() With {.ID = 1,.FName = "J",.Age = 23,.Sex = "M"c})

eList.Add(New Employee() With {.ID = 2,.FName = "M",.Age = 25,.Sex = "F"c})

eList.Add(New Employee() With {.ID = 3,.FName = "A",.Age = 23,.Sex = "M"c})

eList.Add(New Employee() With {.ID = 4,.FName = "K",.Age = 25,.Sex = "M"c})

eList.Add(New Employee() With {.ID = 5,.FName = "L",.Age = 27,.Sex = "F"c})

eList.Add(New Employee() With {.ID = 6,.FName = "J",.Age = 28,.Sex = "M"c})

eList.Add(New Employee() With {.ID = 7,.FName = "K",.Age = 27,.Sex = "F"c})

eList.Add(New Employee() With {.ID = 8,.FName = "J",.Age = 28,.Sex = "M"c})

Return eList
End Function


OUTPUT
image 






About The Author

Suprotim Agarwal
Suprotim Agarwal, Developer Technologies MVP (Microsoft Most Valuable Professional) is the founder and contributor for DevCurry, DotNetCurry and SQLServerCurry. He is the Chief Editor of a Developer Magazine called DNC Magazine. He has also authored two Books - 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook.

Follow him on twitter @suprotimagarwal.

1 comment:

Jeremy said...

You have saved my team many hours. Can you also tell how to add a checkbox to the header so that i select/deselect all checkboxes. I do not want postbacks to occur when I perform this action.