Load local data to JqGrid with paging, sorting and toolbar searching

Hi friends, again i have came up with new article on JqGrid. In past i had written couple of articles.

  1. Get the data from WCF service and assign it to Jqgrid
  2. Get the data from asp.net handler(ashx) and assign it to Jqgrid

But this article is bit different, after reading this you would have a good idea how to assign local data to a jqgrid. You can create own json data and use that. Also you would gain idea for searching, sorting and paging.
Local Data jQGrid
The complete demo is here.
Follow the steps below to create jqgrids

  1. Please download the demo, there you can find the folders css and js. Both the folders are having all the js css file needed for jqgrid.
  2. Add an html file and add the js and css file references to this page.
  3. Please refer the UserList.html file to setup the JqGrid

Below attributes and the values are needed to load the local data
1) datatype
2) datastr
3) jsonReader

Local data Jqgrid
Refer the Screen shot above for visual guidance

Please check the jqgrid definition below:

$(function() {
	//Get the all the data needed for Jqgrid
	//GetAllUsers() method is defined in the UserData.js file
    //This "data" is a global variable and 
	//it is assigned to the "datastr" attribute in Jqgrid definition
	var data = new GetAllUsers();

	$("#UsersGrid").jqGrid({
		//We need 3 attributes to use the local data
		//1) datatype 2) datastr 3) jsonReader
		datatype: 'jsonstring',
		datastr: data,
		//Used to read the data from json object and assign to JqGrid
		jsonReader: {
			root: "rows",
			page: "page",
			total: "total"
		},
		height: 200,
		width: 800,
		//Define your columns Here.
		colNames: ['UserId', 'Name', 'BirthPlace', 'Color'],
		colModel: [ { name: 'UserId', index: 'UserId', width: 100, sorttype: 'integer' },
					{ name: 'Name', index: 'Name', width: 200, sorttype: 'string' },
					{ name: 'BirthPlace', index: 'BirthPlace', width: 200, sorttype: 'string' },
					{ name: 'Color', index: 'Color', width: 100, sorttype: 'string' }
				  ],
		rowNum: 10,
		rowList: [10, 20, 30],
		//This property is very usefull.
		loadonce: true,
		pager: '#UsersGridPager',
		sortname: 'UserId',
		viewrecords: true,
		sortorder: 'asc',
		sortable: true,
		//Change your table name
		caption: 'User Information',
		//Ignore Case while searching
		ignoreCase: true
	});
	jQuery("#UsersGrid").jqGrid('filterToolbar', {
		searchOperators: false,
		searchOnEnter: false,
		autosearch: true,
		defaultSearch: 'cn'
	});
});

You can create your custom Json data to use in JqGrid. Please have a sample codes below:

//Creating user
function User(userId, name, birthPlace, color) {
    this.UserId = userId;
    this.Name = name;
    this.BirthPlace = birthPlace;
    this.Color = color;
}

//This method/constructor would create an object, that jqgrid can receive the data 
function GetAllUsers() {
    var listOfUsers = [];
    listOfUsers[0] = new User(1, "Sibasis Jena", "Bhubaneswar", "Blue");
    listOfUsers[1] = new User(2, "Malaya Sahoo", "Jaggannath Prasad", "Red");
    listOfUsers[2] = new User(3, "Bimal Das", "Kolkata", "Red");
    listOfUsers[3] = new User(4, "Susangeet", "Cuttack", "Black");
    listOfUsers[4] = new User(5, "Tadit Dash", "Nayagarh", "green");
    listOfUsers[5] = new User(6, "Deepak Jena", "Baleswar", "Red");
    listOfUsers[6] = new User(7, "Sisir Jena", "Bhanjanagar", "Blue");
    listOfUsers[7] = new User(8, "Bhikari Nayak", "Bhanjanagar", "Red");
    listOfUsers[8] = new User(9, "Narayan Badhei", "Jaggannath Prasad", "Red");
    listOfUsers[9] = new User(10, "Nalini", "Bhanjanagar", "Red");
    listOfUsers[10] = new User(11, "Lucky", "Aska", "Gray");
    listOfUsers[11] = new User(12, "Jitendra", "Jaggannath Prasad", "LightGray");
    listOfUsers[12] = new User(13, "Bhikari Sahu", "Madhabarida", "Black");
    listOfUsers[13] = new User(14, "Bhaja Jena", "Delhi", "Black");
    listOfUsers[14] = new User(15, "Lingaraj Barik", "Nayagarh", "green");
    listOfUsers[15] = new User(16, "Kumar singh", "Bhanjanagar", "Red");
    listOfUsers[16] = new User(17, "Manas Ranjan", "Bhanjanagar", "Blue");
    listOfUsers[17] = new User(18, "Biswajit", "Bhanjanagar", "Red");
    listOfUsers[18] = new User(19, "Sidhanta", "Jaggannath Prasad", "Red");
    listOfUsers[19] = new User(20, "Akshya", "Bhanjanagar", "Red");
    listOfUsers[20] = new User(21, "Kunumunu", "Bhubaneswar", "Blue");
    listOfUsers[21] = new User(22, "Basant", "Jaggannath Prasad", "Red");
    listOfUsers[22] = new User(23, "Ajit", "Kolkata", "Red");
    listOfUsers[23] = new User(24, "Bulu", "Cuttack", "Black");
    listOfUsers[24] = new User(25, "Gulu", "Nayagarh", "green");
    listOfUsers[25] = new User(26, "DJ jena", "Baleswar", "Red");
    listOfUsers[26] = new User(27, "Prafula", "Bhanjanagar", "Blue");
    listOfUsers[27] = new User(28, "Shivam", "Bhanjanagar", "Red");
    listOfUsers[28] = new User(29, "Narayan Jena", "Jaggannath Prasad", "Red");
    listOfUsers[29] = new User(30, "Vikram", "Bhanjanagar", "Red");
    listOfUsers[30] = new User(31, "Mangulu", "Aska", "Gray");
    listOfUsers[31] = new User(32, "Keshab", "Jaggannath Prasad", "LightGray");
    listOfUsers[32] = new User(33, "Himansu", "Madhabarida", "Black");
    listOfUsers[33] = new User(34, "Jitu", "Delhi", "Black");
    listOfUsers[34] = new User(35, "Satya narayan", "Nayagarh", "green");
    listOfUsers[35] = new User(36, "Uttam", "Bhanjanagar", "Red");
    listOfUsers[36] = new User(37, "Lokanath", "Bhanjanagar", "Blue");
    listOfUsers[37] = new User(38, "Jaga", "Bhanjanagar", "Red");
    listOfUsers[38] = new User(39, "Nilamani", "Jaggannath Prasad", "Red");
    listOfUsers[39] = new User(40, "Tarun Behera", "Bhanjanagar", "Red");
    listOfUsers[40] = new User(41, "Bijay", "Kukudakhandi", "Red");
	
    this.rows = listOfUsers;
    this.page = 1;
    this.total = listOfUsers.length / 10;
}

Select child checkboxes upon selection of parent checkbox

This section will give you a idea on bellow items

1.How to select a group of CheckBoxes at a time.
2.How to use prop method in Jquery.

Description:
On the Parent Check box click 2 things we need to do:
1. Need a selector which will get all the check boxes.
2. Need a Method which will append the checked property to the check boxes.

Note:
Please Copy all the bello Html codes into a Html file and open that file in one browser.
You will see one parent Check box and multiple check boxes.
Please select the parent check box all the Child items will be selected automatically.

Demonstration:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jquery-1.11.0.js"></script>
    <script>
        $(document).ready(function () {
            //The click event will fire by selecting/de-Selecting the Parent CheckBox
            $('#chkSelectAll').click(function (e) {
                //prop method will Add the property to the elements
                //The prop methid will take 2 parameters one is the propertey Name. 2nd one is propertey value
                $('#chkNumber td input:checkbox').prop('checked', this.checked);
            });
        });
    </script>
</head>
<body>
    <div>
        <input type="checkbox" name="chkSelectAll" id="chkSelectAll">
        <label for="chkSelectAll">Select All</label>

        <table style="margin-left: 18px;" id="chkNumber">
            <tbody>
                <tr>
                    <td><input type="checkbox" value="1" name="chkNumber$0" id="chkNumber0"><label for="chkNumber0">One</label></td>
                </tr>
                <tr>
                    <td><input type="checkbox" value="2" name="chkNumber$1" id="chkNumber1"><label for="chkNumber1">Two</label></td>
                </tr>
                <tr>
                    <td><input type="checkbox" value="3" name="chkNumber$2" id="chkNumber2"><label for="chkNumber2">Three</label></td>
                </tr>
                <tr>
                    <td><input type="checkbox" value="4" name="chkNumber$3" id="chkNumber3"><label for="chkNumber3">Four</label></td>
                </tr>
                <tr>
                    <td><input type="checkbox" value="5" name="chkNumber$4" id="chkNumber4"><label for="chkNumber4">Five</label></td>
                </tr>
                <tr>
                    <td><input type="checkbox" value="6" name="chkNumber$5" id="chkNumber5"><label for="chkNumber5">Six</label></td>
                </tr>
                <tr>
                    <td><input type="checkbox" value="7" name="chkNumber$6" id="chkNumber6"><label for="chkNumber6">Seven</label></td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

For your reference:
Please have a look on Jquery Prop Method

Showing Loading Image till the Page ready Using Jquery.

Complete Code here;

How it works:
In my page there are 2 divs
1. loading Image Div
2.Rest of the Page Content.

In the page it self the Loading image Div is visible and The Content Div is hidden.
Just we need to do 2 thing
1.Hide the Loading image Div
2.Unhide the Content Div

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jquery-1.11.0.js"></script>
    <script type="text/javascript">
        window.onload = function () {
            $("#dvLoadingImage").fadeOut(100);
            $("#dvContent").fadeIn(100);
        };
    </script>
    <style>
        #dvLoadingImage {
            color: rgb(119, 69, 233);
            margin-left: 35%;
            margin-top: 13%;
        }
         #dvContent {
            font-size: 152px;
            margin-left: 20%;
            margin-right: 20%;
            display: none;
            background-image: url('Everest_North_Face_toward_Base_Camp_Tibet_Luca_Galuzzi_2006_edit_1.jpg');
        }
    </style>
</head>
<body>
    <div id="dvLoadingImage" >
        <img src="images.jpg" />
    </div>
    <div style="" id="dvContent">
        <span>Body Contents Goes here.</span>
    </div>
</body>
</html>

Handle single quote in Javascript

Download demo project
A better way to handle single Quote in javascript while calling webmethod.
Example
Javascript

 function SaveDetails()
        {
            var name = $("#txtName").val().trim();
            var state = $("#txtState").val().trim();

            //JSON.stringify handle the single quote
            var dataList = JSON.stringify({ Name: name, State: state });

            $.ajax({
                type: "post",
                contentType: "application/json; charset=utf-8",
                url: "login.aspx/SaveDetails",
                data: dataList,
                dataType: "json",
                success: function (data, textStatus) {
                    if (data.d == "true") {
                        alert("success");

                    } else {
                        alert("failed");
                    }
                }
            });
        }

webmethod

 [WebMethod]
        [ScriptMethod]
        public static string SaveDetails(string Name,string State)
        {
            try
            {
                return "true";
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

Reference taken from here

500 Internal Server Error while calling webmethod from javascript

To sole this problem in a better way please refere my new blog Handle single quote in Javascript

Please down load the project
This is the error due to single quote in your input parameter

I am going to explain this issue with an example:
there are two input fields in my page

1. Name
2. State

Case1 :
put any value except single quote in both the fields and submit. it will work fine.

Case2 :
put single quote in name field and in state field put any value. Open firebug console and check
result:500 Internal Server Error

Problem : The single quote is creating problem.

Solution:Replace all the single quote in the value with a &clubs; and in webmethod again  replace all the &clubs; with single quote.

login.aspx:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="login.aspx.cs" Inherits="CallAjaxWebmethod.login" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script src="js/jquery-1.9.0.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        function SaveDetails()
        {
            var name = $("#txtName").val().trim();
            var state = $("#txtState").val().trim();

            //replacing all the single quotes with &clubs;
            name = name.replace(/'/g, '&clubs;');
            state = state.replace(/'/g, '&clubs;');

            //This is the data i am sending to webmethod
            var dataList = "{ 'Name':'" + name + "','State':'" + state + "'}";

            $.ajax({
                type: "post",
                contentType: "application/json; charset=utf-8",
                url: "login.aspx/SaveDetails",
                data: dataList,
                dataType: "json",
                success: function (data, textStatus) {
                    if (data.d == "true") {
                        alert("success");

                    } else {
                        alert("failed");
                    }
                }
            });
        }
    </script>
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table style="width: 100%;">
            <tr>
                <td><span>Name</span></td>
                <td><input id="txtName" type="text" /></td>
            </tr>
            <tr>
                <td><span>State</span></td>
                <td><input id="txtState" type="text" /></td>
            </tr>
            <tr>
                <td colspan="2"><input id="btnSubmit" type="button" value="Save" onclick="SaveDetails()"/></td>
            </tr>
        </table>

    </div>
    </form>

</body>
</html>

login.aspx.cs

using System;
using System.Web.Script.Services;
using System.Web.Services;

namespace CallAjaxWebmethod
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }
        [WebMethod]
        [ScriptMethod]
        public static string SaveDetails(string Name,string State)
        {
            try
            {
                //i am replacing the &clubs; with single quote
                Name = Name.Replace("&clubs;", "'");
                State = State.Replace("&clubs;", "'");

                return "true";
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }
    }
}

To sole this problem in a better way please refere my new blog Handle single quote in Javascript

A simple demo Jqgrid

The jqgrid is filled by Ajax enabled webservice.
Steps:
–Add an ASP.NET Web Application. Automatically a project will be added.
–Add a new Web Form to this project and name this page as “gridcontainer.aspx”
–Add A new project and select WCF Service Application to the existing solution. And name this as MyService.
–Add a new WCF Service(Ajax-enabled) service to Myservice project. Automatically it will add a new service having name as Service2.svc
–Add a Global.asax file to this service.
Here is the total project A simple demo Jqgrid
Please download the project and run the Database scripts in for the table and the procedure.
Please insert some records into the table yourself

Service2.svc.cs content:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace MyService
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service2
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public string GetName()
        {
            // Add your operation implementation here
            return "Sibasis";
        }

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public List GetCompanyList()
        {
            DataTable table = new DataTable("Company");
            SqlConnection con=null;
            List lstCo = new List();

            try
            {
                using (con = new SqlConnection(ConfigurationManager.ConnectionStrings["sibasis"].ConnectionString))
                {
                    con.Open();
                    using ( SqlCommand cmd = new SqlCommand("GetAllCompany", con))
                    {
                        using ( SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                        {
                            adapter.Fill(table);
                        }
                    }
                }

                foreach (DataRow row in table.Rows)
                {
                    Company cmp = new Company();
                    cmp.Id = Convert.ToInt32(row["ID"]);
                    cmp.Name = Convert.ToString(row["Name"]);
                    cmp.Country = Convert.ToString(row["Country"]);
                    cmp.State = Convert.ToString(row["State"]);
                    cmp.Language = Convert.ToString(row["Language"]);

                    lstCo.Add(cmp);
                }
        }
            catch (Exception ex)
            {
                throw ex;
            }
            return lstCo;
        }

        [DataContract]
        public class Company
        {
            [DataMember]
            public int Id { get; set; }
            [DataMember]
            public string Name { get; set; }
            [DataMember]
            public string Country { get; set; }
            [DataMember]
            public string State { get; set; }
            [DataMember]
            public string Language { get; set; }
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

Add the following codes to the Global.asax file in the Myservice project.

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Add the following code in the Myservice web.config file

 <endpointBehaviors>
        <behavior name="MyService.Service2AspNetAjaxBehavior">
          <enableWebScript />
          <webHttp/>
        </behavior>
      </endpointBehaviors>

Then you are ready with the Jqgrid.

Reload Jqgrid on button click

Reload Jqgrid

Call this function on the button click.

Javascript code:
Note:Replace tbSubscriptionGrid with your own Jqgrid id

function ReloadGrid()
{
$("#tbSubscriptionGrid").jqGrid("setGridParam", { datatype: "json" })
 .trigger("reloadGrid", [{ current: true }]);
}

Html code for button:

<input id="btnReload" onclick="ReloadGrid()" type="button" value="button" />

Reference this link for any more information:JqGrid don’i reload after click on the button

Fill JqGrid using Ajax enabled web service.

You can get the project hereindex
If you want to see a demo the go here trirand.com.
Then click on the Searching tab >Toolbar with Operations

This is pretty simple to fill a jqgrid.
1.Create a simple Project with ASP.NET Web application.
2.Add a WCF Service Application to this solution.
3.Make a slightly modification to your web.config in the wcfservice project

   <endpointBehaviors>
        <behavior name="WcfService1.Service2AspNetAjaxBehavior">
          <enableWebScript />
          <webHttp/>
        </behavior>
      </endpointBehaviors>

4.Add an Web Service(Ajax enabled) in the wcfservice project.
Service2.svc
content goes here

using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace WcfService1
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service2
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public List GetCompanyList()
        {
            // Add your operation implementation here
            List lstCo = new List();
            for (int i = 0; i < 20; i++)
            {
                Company cmp= new  Company();
                cmp.Id=1;
                cmp.Name="test";
                cmp.Country = "test";
                cmp.State = "test";
                cmp.Language = "test";
                lstCo.Add(cmp);
            }
            return lstCo;
        }

        [DataContract]
        public class Company
        {
            [DataMember]
            public int Id { get; set; }
            [DataMember]
            public string Name { get; set; }
            [DataMember]
            public string Country { get; set; }
            [DataMember]
            public string State { get; set; }
            [DataMember]
            public string Language { get; set; }
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

2. Add a Global.asax file.
add the following code to Global.asax file

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Then you are ready to go

Bootstrap drop down menu is not working

Please Check the following css and scripts are there in the header section of the page

<script type="text/javascript" src="Scripts/jquery-1.9.0.min.js"></script>
<link href="bootstrap/css/bootstrap.css" rel="Stylesheet" /> 	
<link href="bootstrap/css/bootstrap-theme.css" rel="Stylesheet" />
<script type="text/javascript" src="bootstrap/js/bootstrap.js"></script>

Use the following code:

</pre>
<div class="btn-group"><button class="btn btn-default dropdown-toggle" type="button" data-toggle="dropdown">
 Dropdown

 </button>
<ul class="dropdown-menu">
	<li><a href="#">Dropdown link</a></li>
	<li><a href="#">Dropdown link</a></li>
</ul>
</div>
<pre>

Reference taken from the following site.
http://getbootstrap.com/components/#dropdowns

Row delete + JQGRID

You have to edit in Aspx for the JQgrid defination
Suppose previously you have 4 columns  as following.
colNames: [‘TestimonyID’, ‘Name’, ‘Location’, ‘Approved’]
Now you have to add one new column in defination, now the  colNames will be
colNames: [‘TestimonyID’, ‘Name’, ‘Location’, ‘Approved’,’Delete’]
In colModel you have to add the defination for the Delete column.

<script type="text/javascript">
function deleteClick(Id)
{
       window.location.href = window.location.href + "?deleteid=" + Id;
}

$(function () {
    $("#UsersGrid").jqGrid({
        //Please put your corresponding hanler in place of GrdHandler.ashx
        //I have used handler to fetch data from database.
        url: 'GrdHandler.ashx',
        datatype: 'json',
        height: 250,
        width: 600,
        //Define your columns Here.
        colNames: ['TestimonyID', 'Name', 'Location', 'Approved','Delete'],
        colModel: [
                        { name: 'TestimonyID', index: 'TestimonyID', width: 100, hidden: true, sortable: true, search: true, sorttype: 'integer' },
                        { name: 'Name', index: 'Name', width:200, sortable: true, search: true, sorttype: 'string'},
                        { name: 'Location', index: 'Location', width: 200, sortable: true, search: true, sorttype: 'string' },
                        { name: 'Approved', index: 'Approved', width: 100, sortable: true, search: true, sorttype: 'date' },
                        { name: 'Delete', width: 100, sortable: false, search: false, formatter: function (cellvalue, rowId, rowObject) {
                            var requestName, requestID;
                            if ($.isArray(rowObject)) {
                            //For the first page in grid.
                                // access per array. We are currently in the initial grid filling
                                requestID = rowObject[0];
                            } else {
                                //For the all pages except first page in grid.
                                requestID = rowObject.TestimonyID;
                            }
                            return "<a style="cursor: pointer; text-decoration: underline;" onclick="deleteClick(' + requestID + ')">Delete</a>";
                        }
                        }

                    ],
        rowNum: 10,
        rowList: [10, 20, 30],
        mtype: "GET",
        //This property is very usefull.
        loadonce: true,
        pager: '#UsersGridPager',
        sortname: 'TestimonyID',
        viewrecords: true,
        sortorder: 'asc',
        sortable: true,
        //Change your table name
        caption: 'Testimony Table',
        //Ignore Case while searching
        ignoreCase: true,
        editurl: 'GrdHandler.ashx',
        onPaging: function (b) {
            var nextPg = $(this).getGridParam("page");
            currPg = nextPg;
            return;
        }
    });
    jQuery("#UsersGrid").jqGrid('filterToolbar', { searchOperators: false, searchOnEnter: false, autosearch: true });
});
></script>

In browser the Grid will look like
Delete + Jqgrid
In the code behind get the deleteid from the query string and delete it using your normal code as following

 protected void Page_Load(object sender, EventArgs e)
        {
            int deleteId = 0;

                if (!IsPostBack)
                {
                    //Check the query string deletedId
                    if (int.TryParse(Request.QueryString["deleteid"], out deleteId))
                    {
                        DeleteRecord(deleteId);
                    }
                }

        }
 private void DeleteRecord(int testimonyId)
        {

        }