News Ticker

Menu

Sử dụng jQuery để cố định Datalist Header trong ASP.Net

(How to fix Datalist  Header in ASP.NET Using jQuery) – Trong bài viết trước chúng tôi đã giới thiệu với các bạn cách để cố định Gridview Header. Hôm nay chúng tôi sẽ giới thiệu với các bạn cách để cố định Datalist Header giống như chức năng Freeze trong Excel giúp người dùng dễ dàng xem và  quan sát  kể cả khi danh sách dữ liệu có dài.


Xem những Video hay dành cho thiếu nhi - Nghe trên Youtube



Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET



- B1: Download CSDL Northwind  tại đây và thực hiện công việc Restore Data.

- B2: Tạo Project trong Microsoft Visual Studio 2010

- B3: Download FreezeHedaer Jquery Plugin tại đây, giải nén

- B4: Copy thư mục Js vào Project

B5: Tạo Project trong Microsoft Visual Studio 2010

Trong Visual Studio tạo 1 Class có tên: Utility và nhập đoạn Code phía dưới cho Class này.
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;

namespace FreezeDatalistHeader
{
    public class SqlDataProvider
    {
        #region "Membres Prives"

        private string _connectionString;

        #endregion

        #region "Constructeurs"

        public SqlDataProvider()
        {
            try
            {
                _connectionString = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString;
            }
            catch
            {
            }
        }

        #endregion

        #region "Proprietes"

        public string ConnectionString
        {
            get { return _connectionString; }
        }

        #endregion

        #region "Functions"

        public DataTable FillTable(string sql)
        {
            try
            {
                DataTable tb = new DataTable();
                SqlDataAdapter adap = new SqlDataAdapter(sql, _connectionString);
                adap.Fill(tb);
                return tb;
            }
            catch
            {
                return null;
            }
        }

        #endregion
    }
}

VB.NET Code
Imports System.Data.SqlClient
Imports System.Data

Namespace FreezeDatalistHeader

    Public Class SqlDataProvider

#Region "Membres Prives"

        Shared _IsError As Boolean = False
        Private _connectionString As String

#End Region

#Region "Constructeurs"

        Public Sub New()
            Try
                _connectionString = ConfigurationManager.ConnectionStrings("SiteSqlServer").ConnectionString
                _IsError = False
            Catch ex As Exception
                _IsError = True
            End Try
        End Sub

#End Region

#Region "Proprietes"

        Public ReadOnly Property ConnectionString() As String
            Get
                Return _connectionString
            End Get
        End Property

#End Region

#Region "Functions"

        Public Function FillTable(ByVal sql As String) As DataTable
            Try
                Dim tb As New DataTable
                Dim adap As New SqlDataAdapter(sql, _connectionString)
                adap.Fill(tb)
                Return tb
            Catch ex As Exception
                Return Nothing
            End Try
        End Function

#End Region

    End Class

End Namespace

B6: Mở file Default.aspx dưới dạng HTML và nhập mã HTML
C#
<%@ Page Title="Freeze the Datalist header using Jquery in Asp.net" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="FreezeDatalistHeader._Default" %>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" EnablePageMethods = "true" runat="server">
    </asp:ScriptManager>
    <h3>
        Freeze the Datalist header using Jquery in Asp.net
    </h3>
    <script src="Js/jquery-1.9.1.js" type = "text/javascript"></script>
    <script src="Js/jquery.freezeheader.js" type = "text/javascript"></script>
    <script type = "text/javascript">
        function pageLoad() {
            $("#tblProduct").freezeHeader({ 'height': '350px' });
        };
    </script>
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2" cellspacing="3" width="100%">
                <tr id="trMessage" runat="server" visible="false">
                    <td colspan="2">
                        <asp:Label ID="lblMessage" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:DataList ID="dlObject" runat="server" DataKeyField="ProductID" Width="100%">
                            <HeaderStyle CssClass="GridStyle_HeaderStyle" />
                            <ItemStyle CssClass="GridStyle_RowStyle" />
                            <HeaderTemplate>
                                <table id="tblProduct" cellpadding="2" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                            <th align="center" width="200px">ProductName</th>
                                            <th align="center" width="100px">QuantityPerUnit</th>
                                            <th align="center" width="80px">UnitPrice</th>
                                            <th align="center" width="80px">UnitsInStock</th>
                                            <th align="center" width="80px">UnitsOnOrder</th>                                    
                                        </tr>
                                    </thead>
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <tr class="<%#(Container.ItemIndex+1)%2==0?"GridStyle_AltRowStyle":"GridStyle_RowStyle"%>">
                                        <td align="left" width="200px">
                                            <asp:Label ID="lblProductID" runat="server" Visible="false" Text='<%# Eval("ProductID") %>' />
                                            <asp:Label ID="lblProductName" Text='<%# Eval("ProductName") %>' runat="server"></asp:Label>
                                        </td>
                                        <td align="left" width="100px">
                                            <asp:Label ID="lblQuantityPerUnit" Text='<%# Eval("QuantityPerUnit") %>' runat="server"></asp:Label>
                                        </td>
                                        <td align="right" width="80px">
                                             <asp:Label ID="lblUnitPrice" Text='<%# Eval("UnitPrice") %>' runat="server"></asp:Label>
                                        </td>
                                        <td align="right" width="80px">
                                             <asp:Label ID="lblUnitsInStock" Text='<%# Eval("UnitsInStock") %>' runat="server"></asp:Label>
                                        </td>
                                        <td align="right" width="80px">
                                            <asp:Label ID="lblUnitsOnOrder" Text='<%# Eval("UnitsOnOrder") %>' runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                </ItemTemplate>
                            <FooterTemplate>
                           </table>
                           </FooterTemplate>
                        </asp:DataList>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

VB.NET Code
<%@ Page Title="Freeze the Datalist header using Jquery in Asp.net" Language="vb" MasterPageFile="~/Site.Master" AutoEventWireup="false" EnableEventValidation= "false" CodeBehind="Default.aspx.vb" Inherits="FreezeDatalistHeader._Default" %>

<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <asp:ScriptManager ID="ScriptManager1" EnablePageMethods = "true" runat="server">
    </asp:ScriptManager>
    <h3>
        Freeze the Datalist header using Jquery in Asp.net
    </h3>
     <script src="Js/jquery-1.9.1.js" type = "text/javascript"></script>
    <script src="Js/jquery.freezeheader.js" type = "text/javascript"></script>
    <script type = "text/javascript">
        function pageLoad() {
            $("#tblProduct").freezeHeader({ 'height': '350px' });
        };
    </script>
    <asp:UpdatePanel ID="updatePanel" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <table cellpadding="2" cellspacing="3" width="100%">
                <tr id="trMessage" runat="server" visible="false">
                    <td colspan="2">
                        <asp:Label ID="lblMessage" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <td colspan="2">
                        <asp:DataList ID="dlObject" runat="server" DataKeyField="ProductID" Width="100%">
                            <HeaderStyle CssClass="GridStyle_HeaderStyle" />
                            <ItemStyle CssClass="GridStyle_RowStyle" />
                            <HeaderTemplate>
                                <table id="tblProduct" cellpadding="2" cellspacing="0" width="100%">
                                    <thead>
                                        <tr>
                                            <th align="center" width="200px">ProductName</th>
                                            <th align="center" width="100px">QuantityPerUnit</th>
                                            <th align="center" width="80px">UnitPrice</th>
                                            <th align="center" width="80px">UnitsInStock</th>
                                            <th align="center" width="80px">UnitsOnOrder</th>                                    
                                        </tr>
                                    </thead>
                                </HeaderTemplate>
                                <ItemTemplate>
                                    <tr class="<%# IIf(Container.ItemIndex Mod 2 = 0, "GridStyle_AltRowStyle", "GridStyle_RowStyle") %>">
                                        <td align="left" width="200px">
                                            <asp:Label ID="lblProductID" runat="server" Visible="false" Text='<%# Eval("ProductID") %>' />
                                            <asp:Label ID="lblProductName" Text='<%# Eval("ProductName") %>' runat="server"></asp:Label>
                                        </td>
                                        <td align="left" width="100px">
                                            <asp:Label ID="lblQuantityPerUnit" Text='<%# Eval("QuantityPerUnit") %>' runat="server"></asp:Label>
                                        </td>
                                        <td align="right" width="80px">
                                             <asp:Label ID="lblUnitPrice" Text='<%# Eval("UnitPrice") %>' runat="server"></asp:Label>
                                        </td>
                                        <td align="right" width="80px">
                                             <asp:Label ID="lblUnitsInStock" Text='<%# Eval("UnitsInStock") %>' runat="server"></asp:Label>
                                        </td>
                                        <td align="right" width="80px">
                                            <asp:Label ID="lblUnitsOnOrder" Text='<%# Eval("UnitsOnOrder") %>' runat="server"></asp:Label>
                                        </td>
                                    </tr>
                                </ItemTemplate>
                            <FooterTemplate>
                           </table>
                           </FooterTemplate>
                        </asp:DataList>
                    </td>
                </tr>
            </table>
        </ContentTemplate>
    </asp:UpdatePanel>
</asp:Content>

B7: Viết Code cho file Default.aspx
C# Code
//Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
using Microsoft.VisualBasic;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Diagnostics;

namespace FreezeDatalistHeader
{
    public partial class _Default : System.Web.UI.Page
    {

        #region "Bind Data"

        private void BindProduct()
        {
            DataTable objBind = new DataTable();
            objBind = BindData();

            if (objBind != null)
            {
                if (objBind.Rows.Count > 0)
                {
                    dlObject.DataSource = objBind;
                    dlObject.DataBind();
                    trMessage.Visible = false;
                    dlObject.Visible = true;
                }
                else
                {
                    trMessage.Visible = true;
                    dlObject.Visible = false;
                    lblMessage.Text = "No Data";
                }
                updatePanel.Update();
            }
        }

        public static DataTable BindData()
        {
            SqlDataProvider objSQL = new SqlDataProvider();
            DataTable objBind = objSQL.FillTable("Select Products.* From Products");
            return objBind;
        }

        #endregion

        #region "Event Handles"

        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                if (!IsPostBack)
                {
                    BindProduct();
                }
            }
            catch
            {
            }
        }

        #endregion
    }
}

VB.Net Code
'Visit http://www.laptrinhdotnet.com for more ASP.NET Tutorials
Imports System.Data

Namespace FreezeDatalistHeader

    Public Class _Default
        Inherits System.Web.UI.Page

#Region "Private Methods"

        Private Sub ShowMessage(ByVal ProductID As Integer, ByVal SupplierID As Integer, ByVal CategoryID As Integer)
            Dim sMessage As String = "ProductID: " & ProductID & "\n" & _
                                     "SupplierID: " & SupplierID & "\n" & _
                                     "CategoryID: " & CategoryID
            ScriptManager.RegisterClientScriptBlock(Me.Page, Me.Page.GetType(), "alert", "alert('" & sMessage & "');", True)
        End Sub

#End Region

#Region "Bind Data"

        Private Sub BindProduct()
            Dim objBind As New DataTable
            objBind = BindData()

            If Not objBind Is Nothing Then
                If objBind.Rows.Count > 0 Then
                    dlObject.DataSource = objBind
                    dlObject.DataBind()
                    trMessage.Visible = False
                    dlObject.Visible = True
                Else
                    trMessage.Visible = True
                    dlObject.Visible = False
                    lblMessage.Text = "No Data"
                End If
                UpdatePanel.Update()
            End If
        End Sub

        Private Function BindData() As DataTable
            Dim objSQL As New SqlDataProvider
            Dim objBind As DataTable = objSQL.FillTable("Select Products.* From Products")
            Return objBind
        End Function

#End Region

#Region "Event Handles"

        Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
            Try
                If Page.IsPostBack = False Then
                    BindProduct()
                End If
            Catch ex As Exception

            End Try
        End Sub

#End Region

    End Class

End Namespace

Bây giờ chạy Project bạn sẽ có kết quả như ảnh phía dưới.

Code Example C#, Code Example VB.NET
Code Example C#, Code Example VB.NET




Chúc các bạn thành công!

Quang Bình

Share This:

Post Tags:

Mỗi bài viết đều là công sức và thời gian của tác giả ví vậy tác giả chỉ có một mong muốn duy nhất nếu ai đó có Copy thì xin hãy ghi rõ nguồn và thông tin tác giả ở cuối mỗi bài viết.
Xin cảm ơn!

No Comment to " Sử dụng jQuery để cố định Datalist Header trong ASP.Net "

  • To add an Emoticons Show Icons
  • To add code Use [pre]code here[/pre]
  • To add an Image Use [img]IMAGE-URL-HERE[/img]
  • To add Youtube video just paste a video link like http://www.youtube.com/watch?v=0x_gnfpL3RM