Sei sulla pagina 1di 24

ASP.

NET GridView and jQuery


[Tips & tricks for ASP.NET Gridview and jQuery ]
[In this eBook, find solution for all possible requirements with ASP.NET GridView control with jQuery.]

http://jquerybyexample.blogspot.com

Copyright 2013 jQueryByExample


ALL RIGHTS RESERVED

INTRODUCTION
I am an ASP.NET developer and fan of jQuery. And I am using jQuery extensively with ASP.NET in my work. This eBook has tips and tricks from my blog and these tips and tricks from my reallife experience with ASP.NET GridView control and jQuery.

WHATS IN THIS EBOOK


This eBook takes you through 16 different, useful, tips and tricks and offers solution for all possible requirements with ASP.NET GridView control. This is a point to point eBook with detailed explanation of code. Along with this EBook, sample code samples are also attached which also come with zip package.

WHO IS THIS EBOOK FOR?


This eBook is for developers who are using ASP.NET and JavaScript in their web application. If you are still using JavaScript for ASP.NET GridView control for client side operation, then you will find how to write platform independent and lesser code using jQuery. I assume that you know jQuery basics.

THE BOOKS WEBSITE


Located at http://jquerybyexample.blogspot.com. On this website, you can find solution for many jQuery problems, details about plug-ins, interview questions and much more useful information. You can also follow us on Facebook and Twitter.

My Blog

Page 2

Index
Formatting ASP.NET GridView rows ............................................................................................................. 4 Highlight row on mouseover in ASP.NET GridView ...................................................................................... 4 Set Alternate color for ASP.NET GridView columns...................................................................................... 5 Highlight ASP.NET GridView Rows when Checkbox is checked .................................................................... 6 Change cursor to hand on mouseover in ASP.NET GridView ....................................................................... 8 How to remove ASP.NET GridView rows ...................................................................................................... 9 How to remove ASP.NET GridView columns ................................................................................................ 9 Drag and Drop ASP.NET GridView rows ...................................................................................................... 11 How to loop through all ASP.NET GridView rows ....................................................................................... 11 How to access particular cell in ASP.NET Gridview..................................................................................... 12 How to filter ASP.NET GridView records .................................................................................................... 12 How to search through GridView records .................................................................................................. 15 Get ASP.NET GridView Cell Value on Click .................................................................................................. 18 Check/uncheck checkboxes in Asp.NET GridView ...................................................................................... 20 Highlight empty table element ................................................................................................................... 22 Hide table rows with empty td element ..................................................................................................... 23

My Blog

Page 3

Formatting ASP.NET GridView rows


In this trick, find how to assign alternate background color of ASP.NET Grid Views rows using jQuery. In this example, we will assign grey color to all the odd rows of GridView. When I say Odd that means Rows which are having odd numbers like Row1, Row3, Row5 etc... Lets take an ASP.NET Grid View Control and placed it on ASP.NET Page with ID " gdRows". See below.
<asp:GridView ID="gdRows" runat="server"></asp:GridView>

jQuery provides a selector ":odd" which selects only odd elements. So we need to filter out all the odd rows and assign the color. To filter the rows, we will use filter() method of jQuery, which takes selector as argument and returns the elements which matches the selector. See below jQuery Code.
$(document).ready(function() { $("#<%=gdRows.ClientID%> tr"). filter(":odd").css("background-color", "grey"); });

You can also use ":even" selector to assign other than default color to grid view rows.
$(document).ready(function() { $("#<%=gdRows.ClientID%> tr"). filter(":even").css("background-color", "blue"); });

http://jquerybyexample.blogspot.com/2011/06/formatting-aspnet-gridview-using-jquery.html

Highlight row on mouseover in ASP.NET GridView


In this trick, find how to highlight a gridview row on mouseover. See below image. (The image is not showing the mouse cursor, but the cursor is on 3rd row.)

My Blog

Page 4

All we need to do is that on mouseover on gridview rows assign any CSS and on mouseout, remove that CSS. Rather than using mouseover and mouseout method separately, jQuery provides another method named "hover()" which serves purpose of both the methods. Please read more here about hover(). Below jQuery code, will find all the rows of gridview and using hover method it will assign "LightGrey" color on mouseover and then assign "White" color on mouseout.
$(document).ready(function() { $("#<%=gdRows.ClientID%> tr").hover(function() { $(this).css("background-color", "Lightgrey"); }, function() { $(this).css("background-color", "#ffffff"); }); });

If your default background color for row is other than white then put that color code instead of white. But there is a problem with this code. Which is, that it will assign the mouseover and mouseout effect on header row as well. Try it yourself with above code. So, how to resolve it? Well, we need to change above code little bit so that it finds only those rows which are having "td", not "th". To do this, we can use "has" selector of jQuery to find out all the rows which have td. See below jQuery code.
$(document).ready(function() { $("#<%=gdRows.ClientID%> tr:has(td)").hover(function() { $(this).css("background-color", "Lightgrey"); }, function() { $(this).css("background-color", "#ffffff"); }); });

http://jquerybyexample.blogspot.com/2011/06/highlight-row-on-mouseover-in-gridview.html

Set Alternate color for ASP.NET GridView columns


In this trick, we will see how easily we can assign background color to ASP.NET Grid Views columns using jQuery. In this example, we will assign "Tan" color to all the even columns of GridView and "PaleGoldenrod" to even columns. When I say Odd, which means columns like column1, column3 etc

My Blog

Page 5

$(document).ready(function() { $("#<%=gdRows.ClientID%> td").filter(":even"). css("background-color", "Tan"); $("#<%=gdRows.ClientID%> td").filter(":odd"). css("background-color", "PaleGoldenrod"); });

http://jquerybyexample.blogspot.com/2012/04/set-alternate-color-for-gridview.html

Highlight ASP.NET GridView Rows when Checkbox is checked


In this trick, find jQuery code to highlight ASP.NET Gridview row when checkbox is checked and restore it to original state when unchecked.

My Blog

Page 6

How to do it?

Bind the click event to all the checkbox of ASP.NET GridView.


$('#<%=gdRows.ClientID%>') .find('input:checkbox[id$="chkDelete"]') .click( function() { });

In the click event, first check whether the checkbox is checked or unchecked. And store the status in a variable.
var isChecked = $(this).prop("checked");

After that find the respective row where checkbox is present. As we need to highlight that particular row only.
var $selectedRow = $(this).parent("td").parent("tr");

If you have different color for alternate rows (see above image) then next few lines of code is required, otherwise you can skip it. For example, if all rows of same color then skip this code. But if there is alternate color of GridView rows then it is required. As once we highlight the row, we can't find what the previous color was. So the idea is to find the row index. Based on index value (even or odd) set color value in variable.
var selectedIndex = $selectedRow[0].rowIndex; var sColor = ''; if(selectedIndex%2 == 0) sColor = 'PaleGoldenrod'; else sColor = 'LightGoldenrodYellow

Now based on checkbox status, highlight the row (if checked). Otherwise restore it to previous color which is stored in sColor variable.
if(isChecked) { $selectedRow.css({ "background-color" : "DarkSlateBlue", "color" : "GhostWhite" }); } else { $selectedRow.css({ "background-color" : sColor, "color" : "black" }); }

My Blog

Page 7

So putting it together the complete jQuery code is,


$(document).ready(function() { $('#<%=gdRows.ClientID%>') .find('input:checkbox[id$="chkDelete"]').click(function() { var isChecked = $(this).prop("checked"); var $selectedRow = $(this).parent("td").parent("tr"); var selectedIndex = $selectedRow[0].rowIndex; var sColor = ''; if(selectedIndex%2 == 0) sColor = 'PaleGoldenrod'; else sColor = 'LightGoldenrodYellow'; if(isChecked) $selectedRow.css({ "background-color" : "DarkSlateBlue", "color" : "GhostWhite" }); else $selectedRow.css({ "background-color" : sColor, "color" : "black" }); }); });

Click here to see live demo.


http://jquerybyexample.blogspot.com/2012/12/jquery-highlight-aspnet-gridview-rows-on-checkboxchecked.html

Change cursor to hand on mouseover in ASP.NET GridView


In this trick, find how to change the cursor to Hand style cursor when user takes mouse on the rows of ASP.NET GridView so that the user will come to know that it is clickable. By default, the default cursor appears. Below jQuery code will change the mouse cursor to pointer on hover event.
$(document).ready(function() { $("#<%=gdRows.ClientID%> tr:has(td)").hover(function() { $(this).css("cursor", "pointer"); }); });

http://jquerybyexample.blogspot.com/2011/09/change-cursor-to-hand-on-mouseover-in.html
My Blog Page 8

How to remove ASP.NET GridView rows


In this trick, find how to remove any row in grid view using jQuery. The task is pretty simple. One need to bind the click event with every tr which has only td not th and on click of event removes the clicked row. See below jQuery code.
$(document).ready(function() { $("#<%=gdRows.ClientID%> tr:has(td)").click(function() { $(this).remove(); }); });

Aha...How simple it is...Isn't it? But it would be nice if we show the remove row effect using some animation for better user experience. Well, not to worry when there is jQuery. See below jQuery code.
$(document).ready(function() { $("#<%=gdRows.ClientID%> tr:has(td)").click(function() { $(this).fadeOut(1000, function() { $(this).remove(); }); }); });

[Note: This jQuery code handles only Client Side Updates, not server side. You still need to server side code to delete the row permanently.] http://jquerybyexample.blogspot.com/2011/09/how-to-remove-rows-from-gridviewusing.html

How to remove ASP.NET GridView columns


In this trick, I will show you how to remove columns in grid view on clicking the column header using jQuery. To achieve this, one need to bind the click event on the header columns of the GridView. For your information, GridView is rendered as table > th > tr > td format. So need to bind the click event on "th" to remove the respective column. So first take a look at complete jQuery code to remove columns from GridView.

My Blog

Page 9

See below jQuery code.


$(document).ready(function() { $("#<%=gdRows.ClientID%> th").click(function() { var iIndex = $(this).closest("th").prevAll("th").length; $(this).parents("#<%=gdRows.ClientID%>").find("tr").each(function() { $(this).find("td:eq(" + iIndex + ")").remove(); $(this).find("th:eq(" + iIndex + ")").remove(); }); }); });

Okay, lets understand this code line by line. This below line will bind the click event to all "th" of GridView named "gdRows".
$("#<%=gdRows.ClientID%> th").click(function() {

Now, before removing the column, we need to find out the index of the th or index of the header column which is clicked. The below line of jQuery code, will find the index of the click of the clicked th. The code is using two jQuery selectors "closest()" and "prevAll" to find the out index. The jQuery selector .closest() begins with the current element and travels up the DOM tree until it finds a matching element. And the jQuery selector .prevAll() searches all the predecessors of the current element in the DOM tree.
var iIndex = $(this).closest("th").prevAll("th").length;

Now we need to define a callback function on each row of the GridView to remove td from the each row.
$(this).parents("#<%=gdRows.ClientID%>").find("tr").each(function() {

The below code is placed within the callback function of tr and it will remove the GridView Cells based on the value of iIndex. And it will also remove the th.
$(this).find("td:eq(" + iIndex + ")").remove(); $(this).find("th:eq(" + iIndex + ")").remove();

Instead of removing it, you can also hide the td and th by setting the CSS "display: none". http://jquerybyexample.blogspot.com/2012/03/how-to-remove-gridview-columns-using.html

My Blog

Page 10

Drag and Drop ASP.NET GridView rows


In this trick, find how to rearrange the grid view rows via dragging and dropping rows using jQuery. For your information, GridView is rendered as table format. So to support drag and drop functionality to table rows, we will use plug-in named "TableDnD". This plug-in allows the user to reorder rows within a table. You can download this plug-in from here. All you need to do is to call the function, "tableDnD()" on the grid view and you are done. See below jQuery code.
$(document).ready(function() { $("#<%=gdRows.ClientID%>").tableDnD(); });

You can also add style to let user know that which rows is selected and dropped. To do this, you need to assign a css class to "onDragClass" option of this plug-in.
$(document).ready(function() { $("#<%=gdRows.ClientID%>").tableDnD({ onDragClass: "myDragClass" }); });

http://jquerybyexample.blogspot.com/2012/03/drag-and-drop-gridview-rows-using.html

How to loop through all ASP.NET GridView rows


In this trick, Find that how can you loop through individual rows of ASP.NET GridView using jQuery. You might be knowing that GridView is rendered as table > th > tr > td format. The columns names are placed in th tag and data goes into various td tags. So when you want to loop through all the rows then, just find the rows which have td and are part of ID of your GridView. See below jQuery Code. In this code, the ID of GridView is "gdRows".
$(document).ready(function() { $("#<%=gdRows.ClientID%> tr:has(td)").each(function() { alert($(this).html()); }); });

My Blog

Page 11

If you want to loop through all the rows including th as well, then use below code.
$(document).ready(function() { $("#<%=gdRows.ClientID%> tr").each(function() { alert($(this).html()); }); });

And lastly, if you want to access only th row then


$(document).ready(function() { $("#<%=gdRows.ClientID%> th").each(function() { alert($(this).html()); }); });

http://jquerybyexample.blogspot.com/2012/03/how-to-loop-through-all-grid-view-rows.html

How to access particular cell in ASP.NET Gridview


As you know that GridView is rendered as table > th > tr > td format. Below jQuery code allows to select first cell or td of every row (tr) in GridView. I have used ":eq()" selector to select particular cell.
$(document).ready(function() { $("#<%=gdRows.ClientID%> tr:has(td)").each(function() { var cell = $(this).find("td:eq(0)"); alert(cell.html()); }); });

With ":eq()" selector pass the index of element to select. The ":eq()" selector selects an element with a specific index number. The index numbers start at 0, so the first element will have the index number 0 (not 1). So to select 2nd column then use :eq(1) as the selector. http://jquerybyexample.blogspot.com/2012/04/how-to-access-particular-cell-in.html

How to filter ASP.NET GridView records


In this trick, find how to filter the rows/records of the ASP.NET GridView on client side. When I say filter, that means depending on some condition just show only those records which satisfies the condition

My Blog

Page 12

First take a look at below image.

As you can see from image, that there is a GridView control populated with data and above that there are link buttons for each alphabet along with "All" button. So the problem was, based on the clicked button filter the data from GridView on "ProductName" column. For example, if "H" is clicked, only those products should be visible whose name starts with "H".

And if there are no records that satisfy the condition, then display no records message.

Note: Following controls are placed on the page.


A GridView A Label control which has "No records to display" message. And separate link button for each alphabet and one link button for "All".

My Blog

Page 13

To implement this feature the solution is, When DOM is ready then hide the Label control. Attach click event for Link buttons. I have assigned a class "links" to all link buttons. So using class selector, we can attach the click event. Get the text of the clicked button. Now loop through all the gridview rows and find td with Product Name. Check if the text of td starts with clicked button's text. If yes, then don't hide the row. Otherwise, hide the row.

But we also need to handle the "All" button code and when there are no records then show the label control. The code is very much self explanatory. So putting it together the complete jQuery code is,
$(document).ready(function() { $('#<%=lblNoRecords.ClientID%>').css('display','none'); $('.links').click(function(e) { $('#<%=lblNoRecords.ClientID%>').css('display','none'); var lnkText = $(this).text().toLowerCase(); var iCounter = 0; $("#<%=gdRows.ClientID%> tr:has(td)").each(function() { var cell = $(this).find("td:eq(1)").text().toLowerCase(); if(lnkText != 'all') { if(cell.indexOf(lnkText) != 0) { $(this).css('display','none'); } else { $(this).css('display',''); iCounter++; } } else { $(this).css('display',''); iCounter++; } }); if(iCounter == 0) $('#<%=lblNoRecords.ClientID%>').css('display',''); e.preventDefault(); }); });

http://jquerybyexample.blogspot.com/2012/04/how-to-filter-gridview-records-using.html My Blog Page 14

How to search through GridView records


In this trick, find how to search through all columns of ASP.NET GridView Data and show only those data which satisfies the search text. Take a look at below image.

As you can see from image, that there is a GridView control populated with data and above that there is a textbox and a button. So the problem was, based on the search text entered in search text box, filter the data from GridView on any of the column . For example, "10" is entered then only those rows should be visible which have 10 in any of the column. It can be in ID, ProductName, and Price or quantity column.

My Blog

Page 15

Another example, if "L" is entered then below should be the output.

Note: Following controls are placed on the page.


A GridView A Label control which has "No records to display" message. And separate link button for each alphabet and one link button for "All".
Page 16

My Blog

How to do it? First, hide the "No records to display" label and also hide all the rows of GridView.
$('#<%=lblNoRecords.ClientID%>').css('display','none'); $("#<%=gdRows.ClientID%> tr:has(td)").hide();

Now declare a counter variable, which will be used to display "No records to display" label. And also get the search textbox value.
var iCounter = 0; var sSearchTerm = $('#<%=txtSearch.ClientID%>').val();

If nothing is entered in search textbox, then display all gridview rows and return from here. You can also do validation to show alert message to user to enter something. But I have used Search button as Reset button as well so when nothing is entered, display all the GridView rows.
if(sSearchTerm.length == 0) { $("#<%=gdRows.ClientID%> tr:has(td)").show(); return false; }

Now run a loop through all td elements and within the loop get the td value and compare if the td value matches with the search term. If yes, then show its parent (that is tr) and increment the counter variable.
$("#<%=gdRows.ClientID%> tr:has(td)").children().each(function() { var cellText = $(this).text().toLowerCase(); if(cellText.indexOf(sSearchTerm.toLowerCase()) >= 0) { $(this).parent().show(); iCounter++; return true; } });

Finally, check if counter variable value is equal to 0. If Yes, then display "No records to display" label.
if(iCounter == 0) $('#<%=lblNoRecords.ClientID%>').css('display','');

My Blog

Page 17

So putting it together the complete jQuery code is,


$(document).ready(function() { $('#<%=lblNoRecords.ClientID%>').css('display','none'); $('#<%=btnSubmit.ClientID%>').click(function(e) { // Hide No records to display label. $('#<%=lblNoRecords.ClientID%>').css('display','none'); //Hide all the rows. $("#<%=gdRows.ClientID%> tr:has(td)").hide(); var iCounter = 0; //Get the search box value var sSearchTerm = $('#<%=txtSearch.ClientID%>').val(); //if nothing is entered then shows all the rows. if(sSearchTerm.length == 0) { $("#<%=gdRows.ClientID%> tr:has(td)").show(); return false; } //Iterate through all the td. $("#<%=gdRows.ClientID%> tr:has(td)").children().each(function() { var cellText = $(this).text().toLowerCase(); //Check if data matches if(cellText.indexOf(sSearchTerm.toLowerCase()) >= 0) { $(this).parent().show(); iCounter++; return true; } }); if(iCounter == 0) { $('#<%=lblNoRecords.ClientID%>').css('display',''); } e.preventDefault(); }); });

http://jquerybyexample.blogspot.com/2012/04/how-to-search-through-gridview-records.html

Get ASP.NET GridView Cell Value on Click


In this trick, find how to get ASP.NET GridView Cell Value when it is clicked. You might know that ASP.NET GridView is rendered as table -> th -> tr -> td format. All the rows are converted into tr element and values placed in different td elements.

My Blog

Page 18

So, when the GridView Cell is clicked, for better user experience it is good to highlight the cell. You can also see the same in image. So Below given CSS class, I have used to highlight the selected cell.
.selected { background-color: Yellow; color : Green; }

Before attaching click event to the GridView cells, it is important to let user know that cell is clickable. So change the mouse cursor style to "Pointer" so user will come to know that cell is clickable. Below code exactly does the same thing.
$("#<%=gdRows.ClientID%> tr:has(td)").hover(function(e) { $(this).css("cursor", "pointer"); });

To get the Cell Data, it is important to find out that will cell is clicked. So using "closest()" method, we can find out. The "closest()" method gets the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
$("#<%=gdRows.ClientID%> tr:has(td)").click(function(e) { var selTD = $(e.target).closest("td"); $("#<%=gdRows.ClientID%> td").removeClass("selected"); selTD.addClass("selected"); $("#<%=lblSelected.ClientID%>").html( 'Selected Cell Value is: <b> ' + selTD.text() + '</b>'); });

My Blog

Page 19

The previous jQuery code does following things. First assign a click event to all the tds of GridView. After that it gets the clicked cell into a object using "closest()" method. After it removes selected class from all the tds. This is important as if any cell was previously selected then removes the selected class. Assign selected class to currently clicked cell. And in the end, gets the selected cell's text and assign it to label.

http://jquerybyexample.blogspot.com/2012/05/get-aspnet-gridview-cell-value-on-click.html

Check/uncheck checkboxes in Asp.NET GridView


Find jQuery code to check/uncheck or select/deselect all the checkboxes in ASP.NET Gridview. Assume, all the checkboxes are checked when header checkbox is checked but then you uncheck one of the child checkbox then what happens to your header checkbox? It should also get unchecked. In this trick, find jQuery code to - Check/uncheck all child checkbox based on parent checkbox status. - Update parent checkbox status based on child checkbox status.

My Blog

Page 20

How to do it? Bind the click event to parent checkbox of ASP.NET GridView. In the click event, based on the parent checkbox status set the child checkbox status. Now, based on the child checkbox status also needs to update the parent checkbox. For example, if out of all the child checkboxes, one is unchecked then parent checkbox should also be checked. So for this, attach a click event handler to all the child checkboxes of ASP.NET GridView. In this event, first define a flag with true value. And then loop through all the child checkbox and if one of the child checkbox is unchecked then set the flag value to false. And then update parent checkbox status value based on the flag variable value.

So putting it together the complete jQuery code is,


$(document).ready(function() { $('#gdRows').find('input:checkbox[id$="chkParent"]').click(function() { var isChecked = $(this).prop("checked"); $("#gdRows [id*=chkSelect]:checkbox").prop('checked', isChecked); }); $('#gdRows').find('input:checkbox[id$="chkSelect"]').click(function() { var flag = true; $("#gdRows [id*=chkSelect]:checkbox").each(function() { if ($(this).prop("checked") == false) flag = false; }); $("#gdRows [id*=chkParent]:checkbox").prop('checked', flag); }); });

Click here to see live demo.


http://jquerybyexample.blogspot.com/2013/01/check-and-uncheck-checkboxes-in-asp-net-gridviewusing-jquery.html

My Blog

Page 21

Highlight empty table element


Find jQuery code to highlight those <td> elements within a table/ Grid/ GridView/ DataGrid which have no value associated with it or which are empty. All is required is to loop through all <td> element and check its value. If it is empty, then assign background color to it so that it looks highlighted.
$(document).ready(function() { $("#gdRows td").each(function() { var cellText = $(this).text(); if ($.trim(cellText) == '') { $(this).css('background-color', 'LightGreen'); } }); });

If you want then you can also assign some default data to these empty <td> elements. Using text() method set the default text.
$(document).ready(function() { $("#gdRows td").each(function() { var cellText = $(this).text(); if ($.trim(cellText) == '') { $(this).text('N/A'); } }); });

Click here to see live demo.


http://jquerybyexample.blogspot.com/2012/11/jquery-to-highlight-empty-td-element-table.html My Blog Page 22

Hide table rows with empty td element


Find jQuery code to hide those table rows (<tr>) which have at least one or more <td> element as empty or with no value. To hide table rows, iterate through all td elements and check its text. If it is empty then hide its parent (which is tr) using .hide().
$(document).ready(function() { $("#gdRows tr td").each(function() { var cellText = $.trim($(this).text()); if (cellText.length == 0) { $(this).parent().hide(); } }); });

Click here to see live demo.


http://jquerybyexample.blogspot.com/2012/11/jquery-code-to-hide-table-rows-based-on-td-value.html

My Blog

Page 23

THANKS
So, I guess you have completed this eBook and reached here. I want to thank you for reading this book and everyone who has made this possible. And I feel that you have found this eBook very useful and informative. Please do share your feedback at mailto:jquerybyexample@gmail.com You can also share your feedback on my Blog, Facebook and Twitter. If you like this eBook then subscribe to our latest updates about jQuery. RSS Feed. You can also subscribe via email to get

OTHER USEFUL POST


What is jQuery? jQuery Frequently Asked Questions (FAQ) Mostly asked jQuery interview questions list Detailed guide of how to setup jQuery UI - Part 1 Detailed guide of how to setup jQuery UI - Part 2 All you need to know about jQuery UI Datepicker

My Blog

Page 24

Potrebbero piacerti anche