How to create jQuery scrollable gridview with fix header in asp.net C#,VB

jQuery scrollable gridview with fix header in asp.netIntroduction: In this article i am going to explain How to make scrollable gridview with fix header using jQuery in asp.net with C# and VB languages.

Description: In this article you will learn the following:
  • How to bind gridview with data from sql server table.
  • How to create gridview scrollable keeping header fixed with the help of jQuery as shown in image. 

Implementation:  Let's create a demo website page to demonstrate the concept.

First of all create a DataBase in Sql server and name it e.g.  "DB_Student" and in this database create a table with the following Columns and Data type as shown below and name this table "Tbl_Student". 

Column Name
Data Type
StudentId
Int(Primary Key. So set is identity=true)
StudentName
varchar(100)
Class
varchar(50)
Age
Int
Gender
varchar(50)
Address
varchar(500)

Create a stored procedure to get student details to be filled in GridView Data Control.

CREATE  PROCEDURE [dbo].[GetStudentDetails_SP]
                AS
BEGIN
      SELECT * FROM Tbl_Student
END
  • Now let's connect our asp.net application with Sql Server database
So In the <configuration> tag of web.config file create the connection string as:
  
<connectionStrings>
    <add name="conStr" connectionString="Data Source=LALIT;Initial Catalog=DB_Student;Integrated Security=True"/>
  </connectionStrings>

Note:  Replace the Data Source and Initial Catalog as per your database settings.

  • Below is the HTML Source of the Default.aspx page.

In the <Head> tag paste the following

<%@ 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>Scrollable GridView with Fix Header example</title>

    <link href="CSS/GridviewScroll.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
    <script src="Scripts/gridviewScroll.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            gridviewScroll();
        });

        function gridviewScroll() {
            $('#<%=grdStudentDetails.ClientID%>').gridviewScroll({
                width: 400,
                height: 150,               
                barhovercolor: "#5D7B9D",
                barcolor: "#5D7B9D"
            });
        }
</script>
</head>

<body>
    <form id="form1" runat="server">
    <div>  
<fieldset style="width:400px;">
    <legend>Scrollable GridView with Fix Header</legend>
    <table style="width:100%;">
    <tr>
    <td>
     <asp:GridView ID="grdStudentDetails" runat="server" AutoGenerateColumns="False"  AllowPaging="false" Width="100%"
            CellPadding="4" ForeColor="#333333" GridLines="None">
         <AlternatingRowStyle BackColor="White" ForeColor="#284775" />
        <Columns>
        <asp:BoundField HeaderText="Student Name"  DataField="StudentName" HeaderStyle-HorizontalAlign="Left" />
        <asp:BoundField HeaderText="Class"  DataField="Class" HeaderStyle-HorizontalAlign="Left" />
        <asp:BoundField HeaderText="Age"  DataField="Age" HeaderStyle-HorizontalAlign="Left" />
        <asp:BoundField HeaderText="Gender"  DataField="Gender" HeaderStyle-HorizontalAlign="Left" />
        <asp:BoundField HeaderText="Address"  DataField="Address" HeaderStyle-HorizontalAlign="Left" />    
        </Columns>
         <EditRowStyle BackColor="#999999" />
         <FooterStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
         <HeaderStyle BackColor="#5D7B9D" Font-Bold="True" ForeColor="White" />
         <PagerStyle BackColor="#284775" ForeColor="White" HorizontalAlign="Center" />
         <RowStyle BackColor="#F7F6F3" ForeColor="#333333" />
         <SelectedRowStyle BackColor="#E2DED6" Font-Bold="True" ForeColor="#333333" />
         <SortedAscendingCellStyle BackColor="#E9E7E2" />
         <SortedAscendingHeaderStyle BackColor="#506C8C" />
         <SortedDescendingCellStyle BackColor="#FFFDF8" />
         <SortedDescendingHeaderStyle BackColor="#6F8DAE" />
        </asp:GridView>        
    </td>
    </tr>     
    </table>
    </fieldset>      
    </div>   
    </form>
</body>
</html>

Note: Have you noticed the yellow highlighted two lines in above HTML source? Actually I have linked the required GridviewScroll.css file which is in CSS folder and gridviewScroll.min.js file which is in Scripts folder. You need to download these folders from this link "ScrollableGridViewFixHeaderFiles" and then extract the zipped folder and paste these two folders in the project root folder.

Asp.Net C# Code
  • In code behind file(default.aspx.cs) write the code to bind gridview from sql server database table as:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;

public partial class _Default: System.Web.UI.Page
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conStr"].ConnectionString);
   
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {          
            BindGridView();
        }
    }

    private void BindGridView()
    {
        DataTable dt = new DataTable();
        SqlCommand cmd = null;
        SqlDataAdapter adp = null;
        try
        {           
            cmd = new SqlCommand("GetStudentDetails_SP", con);         
            cmd.CommandType = CommandType.StoredProcedure;
            adp = new SqlDataAdapter(cmd);
            adp.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                grdStudentDetails.DataSource = dt;
                grdStudentDetails.DataBind();
            }
            else
            {
                grdStudentDetails.DataSource = null;
                grdStudentDetails.DataBind();
            }
        }
        catch (Exception ex)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "alert('Oops!! Error occured: " + ex.Message.ToString() + "');", true);
        }
        finally
        {
            con.Close();
            cmd.Dispose();
            adp = null;
            dt.Clear();
            dt.Dispose();
        }
    }
}


Asp.Net VB Code
  • In code behind file (default.aspx.vb) write the code to bind gridview from sql server database table as:

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration

Partial Class _Default
    Inherits System.Web.UI.Page

   Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conStr").ConnectionString)

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        If Not Page.IsPostBack Then
            BindGridView()
        End If
    End Sub

    Private Sub BindGridView()
        Dim dt As New DataTable()
        Dim cmd As SqlCommand = Nothing
        Dim adp As SqlDataAdapter = Nothing
        Try
            cmd = New SqlCommand("GetStudentDetails_SP", con)
            cmd.CommandType = CommandType.StoredProcedure
            adp = New SqlDataAdapter(cmd)
            adp.Fill(dt)

            If dt.Rows.Count > 0 Then
                grdStudentDetails.DataSource = dt
                grdStudentDetails.DataBind()
            Else
                grdStudentDetails.DataSource = Nothing
                grdStudentDetails.DataBind()
            End If
        Catch ex As Exception
            ScriptManager.RegisterStartupScript(Me, Me.[GetType](), "Message", "alert('Oops!! Error occured: " + ex.Message.ToString() + "');", True)
        Finally
            con.Close()
            cmd.Dispose()
            adp = Nothing
            dt.Clear()
            dt.Dispose()
        End Try
    End Sub
End Class


Now over to you:

" I hope you have got the way to make scrollable gridview with fixed header in Asp.Net and If you like my work; you can appreciate by leaving your comments, hitting Facebook like button, following on Google+, Twitter, Linked in and Pinterest, stumbling my posts on stumble upon and subscribing for receiving free updates directly to your inbox . Stay tuned and stay connected for more technical updates." 
Previous
Next Post »

3 comments

Click here for comments
Unknown
admin
June 20, 2014 ×

how to highlight a specific row in a gridview?

Reply
avatar
June 21, 2014 ×

Hello hari dabbiru..read the following article as per your requirement: http://www.webcodeexpert.com/2014/05/change-or-highlight-aspnet-gridview-row.html

Reply
avatar
Unknown
admin
December 07, 2015 ×

How to create a gridview with paging using jQuery ?

Reply
avatar

If you have any question about any post, Feel free to ask.You can simply drop a comment below post or contact via Contact Us form. Your feedback and suggestions will be highly appreciated. Also try to leave comments from your account not from the anonymous account so that i can respond to you easily..