Skip to main content

Jquery read DatakeyNames value of Selected Rows of GridView in Asp.Net

As we know GridView is a very popular control. We always experiment to enhance the GridView control to provide better experience to user. Since javascript is also a popular clientside language, most of the times we use this in client side operations like validation, Row coloring, cell coloring etc. Now a days Jquery is more popular so that in this article i will explain how you can capture the selected rows of a GridView control and also read the datakeyname values using JQuery. So at first i will tell you how we capture selected rows of a GridView. In this example i don't consider the built in Select command. Instead of select command here i use checkbox to select rows by user. The another important tip is we cannot directly access DataKeyNames values of a GridView. To get the value, here I will use a template column to store the same DataKeyValue in a hiddenfield. After that through iteration by Jquery I will read the hiddenfield values which looks alike datakeynames values.

For selecting/deselecting all checkboxes of a GridView using Javascript click here.


My example output look like below:
GridView_Datakeynames_jQuery

The GridView Control HTML will be:
01<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID">  
02            <Columns>  
03                <asp:TemplateField>  
04                    <ItemTemplate>  
05                        <asp:CheckBox ID="chkSelect" runat="server" />  
06                        <asp:HiddenField ID="IDVal" runat="server" Value='<%# Eval("ID") %>' />  
07                    </ItemTemplate>  
08                </asp:TemplateField>  
09                <asp:TemplateField>  
10                    <HeaderTemplate>  
11                        Name  
12                    </HeaderTemplate>  
13                    <ItemTemplate>  
14                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>  
15                    </ItemTemplate>  
16                </asp:TemplateField>  
17            </Columns>  
18        </asp:GridView>

The Jquery Script also given below:
01<script type="text/javascript">  
02    $(document).ready(function() { 
03    var gridView1Control = document.getElementById('<%= GridView1.ClientID %>');  
04    $('#<%= cmdGetData.ClientID %>').click(function (e) {
05        var DataKeyName=""
06        $('input:checkbox[id$=chkSelect]:checked', gridView1Control).each(function (item, index) {  
07            if(DataKeyName.length==0)
08            {
09                DataKeyName = $(this).next('input:hidden[id$=IDVal]').val();
10            }
11            else
12            {
13                DataKeyName += "," + $(this).next('input:hidden[id$=IDVal]').val();
14            }
15        });  
16        alert(DataKeyName);
17        return false;  
18    });  
19   });  
20</script>

Now Bind the GridView data within Page_Load Event:
01protected void Page_Load(object sender, EventArgs e)
02    {
03        DataTable dt = new DataTable();
04 
05        dt.Columns.Add("ID");
06        dt.Columns.Add("Name");
07 
08        DataRow oItem = dt.NewRow();
09        oItem[0] = "1";
10        oItem[1] = "Shawpnendu Bikash Maloroy";
11        dt.Rows.Add(oItem);
12 
13        oItem = dt.NewRow();
14        oItem[0] = "2";
15        oItem[1] = "Bimalendu Bikash Maloroy";
16        dt.Rows.Add(oItem);
17 
18        oItem = dt.NewRow();
19        oItem[0] = "3";
20        oItem[1] = "Purnendu Bikash Maloroy";
21        dt.Rows.Add(oItem);
22 
23        GridView1.DataSource = dt;
24        GridView1.DataBind();
25 
26    }

The complete markup language of this example is:
01<%@ Page Language="C#" AutoEventWireup="true" CodeFile="GridView_DataKeyNames_Jquery.aspx.cs" Inherits="GridView_DataKeyNames_Jquery" %>
02 
03<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
04 
05<html xmlns="http://www.w3.org/1999/xhtml" >
06<head runat="server">
07<title>Get Selected rows of a GridView using Jquery</title>
08<script src="Script/jquery.js" type="text/javascript"></script>
09 
10<script type="text/javascript">  
11    $(document).ready(function() { 
12    var gridView1Control = document.getElementById('<%= GridView1.ClientID %>');  
13    $('#<%= cmdGetData.ClientID %>').click(function (e) {
14        var DataKeyName=""; 
15        $('input:checkbox[id$=chkSelect]:checked', gridView1Control).each(function (item, index) {  
16            if(DataKeyName.length==0)
17            {
18                DataKeyName = $(this).next('input:hidden[id$=IDVal]').val();
19            }
20            else
21            {
22                DataKeyName += "," + $(this).next('input:hidden[id$=IDVal]').val();
23            }
24        });  
25        alert(DataKeyName);
26        return false;  
27    });  
28   });  
29</script>  
30     
31</head>
32<body>
33    <form id="form1" runat="server">
34    <div>
35        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false" DataKeyNames="ID">  
36            <Columns>  
37                <asp:TemplateField>  
38                    <ItemTemplate>  
39                        <asp:CheckBox ID="chkSelect" runat="server" />  
40                        <asp:HiddenField ID="IDVal" runat="server" Value='<%# Eval("ID") %>' />  
41                    </ItemTemplate>  
42                </asp:TemplateField>  
43                <asp:TemplateField>  
44                    <HeaderTemplate>  
45                        Name  
46                    </HeaderTemplate>  
47                    <ItemTemplate>  
48                        <asp:Label ID="Label1" runat="server" Text='<%# Eval("Name") %>'></asp:Label>  
49                    </ItemTemplate>  
50                </asp:TemplateField>  
51            </Columns>  
52        </asp:GridView>  
53   
54         
55    
56        <asp:Button ID="cmdGetData" runat="server" Text="Get Data" />   
57    </div>
58    </form>
59</body>
60</html>

Comments

Popular posts from this blog

Scrollable GridView with Fixed Headers using jQuery Plugin

Using the same example I have created a jQuery Plugin for Scrollable GridView with Fixed header so that you can directly make a GridView scrollable.   HTML Markup < form   id ="form1"   runat ="server"> < asp : GridView   ID ="GridView1"   runat ="server"   AutoGenerateColumns   =   "false"> < Columns > < asp : BoundField   DataField   =   "ContactName"   HeaderText   =   "Contact Name"   /> < asp : BoundField   DataField   =   "City"   HeaderText   =   "City"   /> < asp : BoundField   DataField   =   "Country"   HeaderText   =   "Country"   /> Columns > asp : GridView > form >   Applying the Scrollable Grid jQuery Plugin < script   src ="Scripts/jquery-1.4.1.min.js"   type ="text/javascript"> script > < script   src ="Scripts/Scro...

GRIDVIEW GROUPING

When displaying data, we sometimes would like to group data for better user experience or when displaying long list of hierarchal data, we would want to display them in a tree view kind of structure. There is more than way of doing this, but I am going to explain achieving this functionality using  AJAX Collapsible Panel Extender Control . Overview: I am going to use  Adventure Works  as datasource. Every product in  Production.Product  table belongs to a product sub category. We fetch handful of products and the sub categories they belong to from the database. Our objective is to list all the available sub categories and allow user to  expand/collapse  to look/hide the list of products belonging to each subcategory. Database Connection Added following entry under  connectionStrings  element in  web.config . < add   name = "Sql"   connectionString="Data Source=(local); Initial  Catalog = AdventureWorks ...

ADO.NET Concepts With example

COMMAND OBJECT  Command object is the biggest object in ADO.NET  It is the only object which can perform actions with database  It  can be created directly using Command class or can be created using Connection.Create command (factory classes also contain creation of Command). Ex:  SqlConnection sqlCon = new SqlConnection("......");    SqlCommand sqlCmd = sqlCon.CreateCommand();  Commands that we run depend upon the kind of query that we want to execute with database. All databases support two types of queries. i. Action Queries ii. Non-action Queries Action queries are those which change the state of database and which don‟t return any query results(though they return the number of records affected). Ex: Insert, Delete and Update statements Non-action queries are those which don‟t affect the database but return the results to the user. Ex: Select statement Method of execution of queries: Command object provides the following methods to execute queries: 1. Ex...