Format GridView table rows using jQuery

In this article we will see as how we can give alternating color to alternating rows of GridView using jQuery. Here we will use Northwind Database for the purpose of demonstration.

First, let's make connection in the web.config

WEB.CONFIG

<connectionStrings>

<add name="NORTHWNDConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integrated Security=True;User Instance=True"

providerName="System.Data.SqlClient" />

</connectionStrings>

 

Second, we will include a Stylesheet in which we will write a class to give a different background color to rows of gridview. For the sake of simplicity the name of our style is Style.css

STYLE.CSS

 

.gridviewOdd

{

background-color:Aqua;

}

.gridviewEven

{

background-color:Lime;

}

 

 

Third, we will create a webpage that includes a gridview. Here we are using SQLDataSource to get data from Suppliers table of NorthWind Database

Default.aspx

 

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

 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server" >

<title>Demo For GridView</title>

<link href="Style.css" rel="stylesheet" type="text/css" />

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

<script type="text/javascript">

$(document).ready(function () {

$('#GridView2 tr:odd').addClass('gridviewOdd');

$('#GridView2 tr:even').addClass('gridviewEven');

 

}

);

 

</script>

</head>

<body>

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

 

<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False"

DataKeyNames="SupplierID" DataSourceID="SqlDataSource1"

EmptyDataText="There are no data records to display.">

<Columns>

<asp:BoundField DataField="SupplierID" HeaderText="SupplierID" ReadOnly="True"

SortExpression="SupplierID" />

<asp:BoundField DataField="CompanyName" HeaderText="CompanyName"

SortExpression="CompanyName" />

<asp:BoundField DataField="ContactName" HeaderText="ContactName"

SortExpression="ContactName" />

<asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle"

SortExpression="ContactTitle" />

 

</Columns>

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

ConnectionString="<%$ ConnectionStrings:NORTHWNDConnectionString1 %>"

ProviderName="<%$ ConnectionStrings:NORTHWNDConnectionString1.ProviderName %>"

SelectCommand="SELECT top(50) [SupplierID], [CompanyName], [ContactName], [ContactTitle] FROM [Suppliers]">

</asp:SqlDataSource>

</form>

</body>

</html>

 

Result:

 

 

 

Tags: , ,

ASP.NET | jQuery