(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.


Nghe những bài hát đỉnh nhất về Thấy cô giáo - 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 stringConnectionString
        {
            get { return_connectionString; }
        }

        #endregion

        #region"Functions"

        public DataTableFillTable(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 AsString

#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() AsString
            Get
                Return _connectionString
            End Get
        End Property

#End Region

#Region "Functions"

        Public FunctionFillTable(ByVal sql AsString) As DataTable
            Try
                Dim tb AsNew DataTable
                Dim adap AsNew 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#
<%@ PageTitle="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%">
                <trid="trMessage"runat="server"visible="false">
                    <tdcolspan="2">
                        <asp:Label ID="lblMessage" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <tdcolspan="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
<%@ PageTitle="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%">
                <trid="trMessage"runat="server"visible="false">
                    <tdcolspan="2">
                        <asp:Label ID="lblMessage" runat="server"></asp:Label>
                    </td>
                </tr>
                <tr>
                    <tdcolspan="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 voidBindProduct()
        {
            DataTable objBind = newDataTable();
            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 = newSqlDataProvider();
            DataTable objBind = objSQL.FillTable("Select Products.* From Products");
            return objBind;
        }

        #endregion

        #region"Event Handles"

        protected voidPage_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 SubShowMessage(ByVal ProductID As Integer, ByVal SupplierID As Integer, ByValCategoryID 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 SubBindProduct()
            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 FunctionBindData() 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 SubPage_Load(ByVal sender AsObject, 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

0 comments Blogger 0 Facebook

Post a Comment

 
lập trình đốt nét © 2013. All Rights Reserved. Powered by Blogger
Top