ASP.NET GridView + jQuery tips and tricks - Part 2

SheoNarayan
Posted by in ASP.NET category on for Intermediate level | Views : 125674 red flag
Rating: 5 out of 5  
 3 vote(s)

This article demonstrate how to do CRUD operation using GridView and jQuery seamlessly (without page refresh) and also describes some simple UI effects in ASP.NET GridView control using jQuery.

This is the Part 2 and last part of this article.


 Download source code for ASP.NET GridView + jQuery tips and tricks - Part 2

Pre-requisite

Before you proceed with this article, please read its first part that explains how CRUD (Create, Read, Update and Delete) operations are performed based on commanda sent from this page using jQuery.

Go to first part of this article, ASP.NET GridView + jQuery UI tips and tricks - Part 1 .

Video of this article

 You can watch the video of this article at http://www.dotnetfunda.com/tutorials/videos/x73-aspnet-gridview--jquery-tips-and-tricks-.aspx

Lets talk about default.aspx page now that do all the tricks

In order to bring the selected row, highlighted row and others necessary effects as shown in the below picture, I have kept couple of .css classes on this default.aspx page, they are following

<head runat="server">

<title>Edit GridView</title>

<style type="text/css">

th

{

text-align:left;

}

 

body

{

font-family:Arial;

font-size:10pt;

}

 

#divEditBox

{

display:none;

position:absolute;

left:30%;

top:30%;

}

 

.highlightRow

{

background-color:Yellow;

}

 

.select

{

background-color:#c0c0c0;

}

</style>

<script language="javascript" src="jquery-1.4.min.js" type="text/javascript"></script>

</head>

.css code on default.aspx page

The first th class simply keep the header of the GridView left aligned, body is to just make the body font as arial and font-size as 10pt. .divEditBox class is the one that shows the selected record to edit at the center of the page. .highlightRow is the class that is set to the row when mouse overing the row and .select css class is set to the row when user clicks it. 

I have also referred the jQuery .js file that you can download from http://jquery.com/. Alternately, you can also refer the Microsfot AJAX CDN jQuery file from http://www.asp.net/ajaxlibrary/cdn.ashx as shown below.

 <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js" type="text/javascript"></script>

GridView jQuery UI tips and tricks

Now, lets see the HTML code from default.aspx page

<form id="form1" runat="server">

<p><a href="javascript:void(0)" onclick="LoadGridViewData(0, 1)">Load</a> | <a id="addLink" href="javascript:void(0)" title="Add">Add</a></p>

<div id="divGridViewData"></div>

<div id="divEditBox">

<table cellpadding="4" width="600" cellspacing="0" border="0" style="background-color:#efefef;border:1px solid #c0c0c0;">

<tr style="background-color:#b0b0b0;" valign="top">

<td style="width: 91%" colspan="3">&nbsp;<label id="lblPopTitle">Modify Record</label></td>

<td align="right" style="width: 9%;padding-right:10px;">

<a id="closeLink" href="javascript:void(0)" onclick="HideEditBox()" title="Close">Close</a>

</td>

</tr>

<tr>

<td>Name: </td><td><input type="text" id="txtEditName" />

</td>

<td>Address: </td><td><input type="text" id="txtEditAddress" /></td>

</tr>

<tr>

<td>Phone: </td><td><input type="text" id="txtEditPhone" size="10" /></td>

<td>City: </td><td><input type="text" id="txtEditCity" size="10" /></td>

</tr>

<tr><td colspan="4" align="center">&nbsp;

<input type="button" value="Submit" onclick="UpdateInsertData()" />

<input type="hidden" id="editId" value="0" />

</td></tr>

</table>

</div>

</form>

.html code on default.aspx page

This has two links called Load and Add that is used to Load the GridView data and to list the add record box as shown in the picture below. The same box is used to bring the record into Edit mode as well. Apart from these, I also have a div with Id divGridViewData but there is nothing inside as I have kept this as placeholder and I shall be using this to populate my asp:GridView control data.

On click event of the Submitt button, I have specified UpdateInsertDate() function that will send proper command to the GridViewData.aspx page (expained in the first part of this article).

To find out the selected record, I have kept a hidden field on this page named editId that is used to set the value of the selected record.

Now, lets see the jQuery functions kept on this page.

You may notice that I have used jQuery post method to post the required parameters to the GridViewData.aspx page (explained in the first part of this article). In that page, I have retrieved these parameters value using Request.Form object.

A little about jQuery post method.

jQuery post method is used to send the data to another page, it waits for the response from another page and gives you back. For example, in the below code snippets, the data is sent to the GridViewData.aspx page with two form element startRowIndex and thisPage.

function LoadGridViewData(start, pageNo) {

$(document).ready(function() {

$.post("GridViewData.aspx", {

startRowIndex: start,

thisPage: pageNo

},

function(data) {

$("div#divGridViewData").html(data);

});

});

}

On GridViewData.aspx page, I can retrive its value using following code snipept.

_startRowIndex = int.Parse(Request.Form["startRowIndex"].ToString());

_thisPage = int.Parse(Request.Form["thisPage"].ToString());

Once the data has been sent with the required parameter, it waits for the response from that page that can be catched and used. Here my response is the binded rendered GridView that I have set as innerHTML into my div with id divGridViewData.

The complete jQuery / javaScript functions of default.aspx page

<script language="javascript" type="text/javascript">

// Load the gridview page data

function LoadGridViewData(start, pageNo) {

$(document).ready(function() {

$.post("GridViewData.aspx", {

startRowIndex: start,

thisPage: pageNo

},

function(data) {

$("div#divGridViewData").html(data);

});

});

}

 

// insert / update the data

function UpdateInsertData() {

$(document).ready(function() {

$.post("GridViewData.aspx",

{

pName : $("#txtEditName").val(),

pAddress: $("#txtEditAddress").val(),

pCity : $("#txtEditCity").val(),

pPhone : $("#txtEditPhone").val(),

editId : $("#editId").val()

},

function(data) {

$("div#divGridViewData").html(data);

});

});

 

// hide the edit box

HideEditBox();

}

 

// delete the record

function DeleteRecord(id) {

$(document).ready(function() {

$.post("GridViewData.aspx",

{

deleteId: id

},

function(data) {

$("div#divGridViewData").html(data);

});

});

}

 

// show edit box when edit link is clicked

function ShowEditBox(id)

{

$("#divEditBox").slideDown("medium");

var pid = 'PName' + id;

var colIndex = 0;

var $tr = $("#" + pid).parent().parent();

 

$tr.find('td').each(function() {

if (colIndex == 2) {

$("#txtEditName").val($(this).text());

}

else if (colIndex == 3) {

$("#txtEditAddress").val($(this).text());

}

else if (colIndex == 4) {

$("#txtEditCity").val($(this).text());

}

else if (colIndex == 5) {

$("#txtEditPhone").val($(this).text());

}

colIndex++;

})

$("#editId").val(id);

}

 

// Hide the edit/insert box

function HideEditBox() {

$("#divEditBox").slideUp("medium");

}

// show the box when add link is clicked

$(document).ready(function() {

// when add link will be clicked

$("#addLink").click(function() {

$("#divEditBox").slideDown("medium");

$("#txtEditName").val("");

$("#txtEditAddress").val("");

$("#txtEditCity").val("");

$("#txtEditPhone").val("");

$("#editId").val("0");

$("#lblPopTitle").text("Add Record");

})

})

</script>

.jQuery / javaScript code on default.aspx page

The above code snippet contains following javaScript functions

  • LoadGridViewData() - This accepts two parameters, start (start row number from where the records should be fetched from the database) and pageNo (the current page number).
  • UpdateInsertData() - This function retrives the TextBox value set by ShowEditBox() function explained below and send the data to the GridViewData.aspx page to update or insert. In case of Update the editId value is set to the AutoId column value from database else 0.
  • DeleteRecord() - This function get the selected record id and send to the GridViewData.aspx page for deletion.
  • ShowEditBox() - This function sets the selected record in edit mode and let the user edit the record.
  • HideEditBox() - This function simply hide the EditBox.
  • The last function fires when Add link is clicked from the top-left of the page.

Update Mode of the GridView

Now lets see the Code behind page of default.aspx

Look at the following code snippet, Surprise? Yes, there will not be anything in the default.aspx code behind as we are not doing anything from server side on this page. This page just do all client side activities and all server side activities (listing, deleting, adding, updating) are taken care by GridViewData.aspx page explained in the first part of this article.

using System;

using System.Data;

using System.Data.SqlClient;

using System.Configuration;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

public partial class GridViewList : System.Web.UI.Page

{

/// <summary>

/// Handles the Load event of the Page control.

/// </summary>

/// <param name="sender">The source of the event.</param>

/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>

protected void Page_Load(object sender, EventArgs e)

{

}

}

 

Lets Sum up what we did here

The concept of doing CRUD opertion seamlessly without even a single browser refresh in GridView using jQuery is that the default.aspx page will work as placeholder for the GridView and also work as command page where all necessary commands are fired.

All CRUD opertions that need server side activities are taken care by GridViewData.aspx page, even simple jQuery client side effects like selecting the row by clicking and mouseover effects etc are taken care by GridViewData.aspx page. Default.aspx page just instructs the GridViewData.aspx page using jQuery by sending necessary command to do the operations.

Lets go through some asp:GridView and jQuery simple tips and tricks

 

Highlighting an ASP.NET GridView row on Mouse Over

To highlight the row on mouse over, get the reference of the mouse hover row and add the css class named .highlightRow and if mouse Out simply remove this class.

// highlight the row when clicked

$(document).ready(function () {

$("#divGridView table tbody tr").mouseover(function () {

$(this).addClass("highlightRow");

}).mouseout(function () { $(this).removeClass('highlightRow'); })

});

 

Select / Highlight ASP.NET GridView row by clicking it

To select the row on which mouse click has happened, just get the reference of the clicked row and add the css class called .select.

// highlight row by clicking it

$(document).ready(function () {

$("#divGridView table tbody tr").click(function () {

$(this).addClass("select");

})

});

 

Remove / Delete the ASP.NET GridView row by double clicking

The same as above, get the reference of the double clicked row and get the id of that record. I have get the id of the selected record by finding the first column of the row by using td:first and retrieved its text. Once I have the id, I passed this to DeleteRecord javascript function that in tern instruct the GridViewData.aspx page to delete the record. To hide that row from client side, I removed that row using jQuery remove() method.

// double click delete rows

$(document).ready(function () {

$("#divGridView table tbody tr").dblclick(function () {

// find the id first

var v = confirm('Are you sure to delete?');

if (v) {

var autoId = $(this).find("td:first").text();

 

// remove the row from server side (the database)

DeleteRecord(autoId);

 

// remove from the clien side

$(this).remove();

}

})

});

 

In case you do not want to remove the record from the data, simply comment other lines except $(this).remove();

Go to first part of this article (ASP.NET GridView + jQuery UI tips and tricks - Part 1) to understand this completely.

Conclusion

In this article, I have explained how to use ASP.NET GridView and jQuery to seamlessly list, insert, update and delete records. Even pagination can be done wtihout any page refresh.

Hope you liked this article. The entire source code of this article can be downloaded from top of this article.

Thanks for reading. Wish you a happy learning and keep learning and sharing knowledge.

Page copy protected against web site content infringement by Copyscape

About the Author

SheoNarayan
Full Name: Sheo Narayan
Member Level: HonoraryPlatinum
Member Status: Administrator
Member Since: 7/8/2008 6:32:14 PM
Country: India
Regards, Sheo Narayan http://www.dotnetfunda.com

Ex-Microsoft MVP, Author, Writer, Mentor & architecting applications since year 2001. Connect me on http://www.facebook.com/sheo.narayan | https://twitter.com/sheonarayan | http://www.linkedin.com/in/sheonarayan

Login to vote for this post.

Comments or Responses

Posted by: Poster on: 7/31/2010
The way of finding the clicked / selected row is much better than explained other places.

Good one.
Posted by: Syful on: 12/29/2010 | Points: 25
where is the SampleDatabase u used???
Posted by: SheoNarayan on: 12/29/2010 | Points: 25
Answered in the first part of this article. Thanks!
Posted by: Brajesh.mahor on: 4/22/2011 | Points: 25
realy very nice...
Posted by: Rahulpriyan on: 8/22/2011 | Points: 25
Excellent Article... Really Nice..

I used your above article in my project.

I hav a search ASP:LinkButton and filter textboxes in the gridviewdata.aspx page..

Wen i try to click the search button the postback occurs and only gridviewdata.aspx page displays. I dont want to pass the search paramters as in ShowEditBox

Can u help to get out of this situation..??

Btw, Very Thanks 4 this nice article..

Login to post response

Comment using Facebook(Author doesn't get notification)