Sunday, July 3, 2011

JQuery - Formatting GridView Using JQuery

In this article i will show you how we can assign alternate background color of ASP.NET Grid Views rows using jQuery.

Step 1
Download JQuery Script from the following Link

Step 2
Create a Web Application and give the Solution name as SolFormattingGridView_Jquery

Step 3
Add a grid view control on page it is look like this
        <asp:GridView ID="GvDeveloper" runat="server" >

Step 4
Add jQuery file Reference inside the head tag of the page,it is look like this
<head runat="server">
    <title>Formatting GridView using Jquery</title>

    <script src="Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>


Step 5
Create a CSS for formatting GridView,it is look like this

Step 6
Write a JQuery script for formatting a gridview,it is look like this

jQuery provides  ":odd" and ":even" selector. ":odd" selector which selects only odd elements. ":even" selector which selects even elements.
in short  Rows which are having odd numbers like Row1, Row3, Row5 etc. and even number like   Row2,Row4,Row6 etc.
So we need to filter out all the odd rows and even rows for 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.
then Adds the specified css classes to each of the set of matched elements.

Run the project.

Note: Dose not show code behind on post.


Click on image for better view

Full Code
          .aspx Code
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">

<html xmlns="">
<head runat="server">
    <title>Formatting GridView using Jquery</title>

    <style type="text/css">

    <script src="Scripts/jquery-1.6.1.min.js" type="text/javascript"></script>

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

        $(document).ready(function () {

            // Header Color
            $("#GvDeveloper th").addClass("HeaderColor");

            // Alternative Row Color
            $("#GvDeveloper tr").filter(":odd").addClass("AlterNativeRowColor");

            // Default Row Color 
            $("#GvDeveloper tr").filter(":even").addClass("DefaultRowColor");



    <form id="form1" runat="server">
        <asp:GridView ID="GvDeveloper" runat="server" >

Download Source Code

1 comment: