ASP.NET 如何固定表格表頭(fixed header)

你在HTML中渲染一張表格(可能是GridView或者Repeater),如果表格的行數太多,你就得向下拖東滾動條,但你一旦向下拖動滾動條,表頭的信息就不見了。具體見下圖。

ASP.NET 固定表頭 - 1

向下拖動滾動條後,表頭信息消失:

ASP.NET 固定表頭 - 2

在本文中,我向大家講解如何固定住表頭。網上可以搜索到很多種方法來實現這個功能,但這些方法基本的原理都是一樣的。就是利用div,將表頭的信息複製到表身之上的一個div中。

 

1 <div> 表頭 </div>
2 <div> 表身 </div>

 

滾動條只在表身div中,這樣拖動表身div就不會影響到表頭的div了。

經過我的實驗,有以下兩個具體的方法比較好用,分別適用於ASP.NET的Repeater控件和GridView控件。

(一)用於Repeater控件:

webForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication1.WebForm1" %>

<!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></title>
    <script type="text/javascript" language="javascript">
        function FixTableHeader() {
            var t = document.getElementById("table");
            var thead = t.getElementsByTagName("thead")[0];
            var t1 = t.cloneNode(false);
            t1.appendChild(thead);
            document.getElementById("tableHeader").appendChild(t1)
        }
        window.onload = FixTableHeader;
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="tableHeader">
    </div>
    <div style="overflow: scroll; height: 100px; width: 500px">
        <table id="table" width="500" style="table-layout: fixed">
            <thead>
                <tr id="thead" style="background-color: #BEBEBE">
                    <th>
                        Account Number
                    </th>
                    <th>
                        Account Name
                    </th>
                    <th>
                        City
                    </th>
                    <th>
                        Country
                    </th>
                </tr>
            </thead>
            <tbody>
                <asp:Repeater ID="Reapeter1" runat="server">
                    <ItemTemplate>
                        <tr>
                            <td>
                                <%#DataBinder.Eval(Container.DataItem, "AccountNumber")%>
                            </td>
                            <td>
                                <%#DataBinder.Eval(Container.DataItem, "AccountName")%>
                            </td>
                            <td>
                                <%#DataBinder.Eval(Container.DataItem,"City")%>
                            </td>
                            <td>
                                <%#DataBinder.Eval(Container.DataItem,"Country")%>
                            </td>
                        </tr>
                    </ItemTemplate>
                </asp:Repeater>
            </tbody>
        </table>
    </div>
    </form>
</body>
</html>

 

注意,如果你想表頭和表身的每一列都對齊的話,table的style="table-layout: fixed"不能少。

C#代碼:

using System;
using System.Web.UI;
using System.Data;

namespace WebApplication1
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn("AccountNumber"));
                dt.Columns.Add(new DataColumn("AccountName"));                                   
                dt.Columns.Add(new DataColumn("City"));
                dt.Columns.Add(new DataColumn("Country"));
                DataRow dr = dt.NewRow();
                dr["AccountName"] = "Test1"; 
                dr["AccountNumber"] = "001"; 
                dr["Country"] = "China"; 
                dr["City"] = "Beijing"; 
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["AccountName"] = "Test2";
                dr["AccountNumber"] = "002";
                dr["Country"] = "China"; 
                dr["City"] = "Shanghai"; 
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["AccountName"] = "Test3"; 
                dr["AccountNumber"] = "003"; 
                dr["Country"] = "the Nederlands"; 
                dr["City"] = "Amsterdam"; 
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["AccountName"] = "Test4"; 
                dr["AccountNumber"] = "004"; 
                dr["Country"] = "France"; 
                dr["City"] = "Paris"; 
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["AccountName"] = "Test5"; 
                dr["AccountNumber"] = "005"; 
                dr["Country"] = "Spain";
                dr["City"] = "Barcelona"; 
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["AccountName"] = "Test6"; 
                dr["AccountNumber"] = "006"; 
                dr["Country"] = "China"; 
                dr["City"] = "Shanghai"; 
                dt.Rows.Add(dr);
                Reapeter1.DataSource = dt;
                Reapeter1.DataBind();
            }
        }
    }
}

 

最後的效果爲:

ASP.NET 固定表頭 - 3

ASP.NET 固定表頭 - 4

(二) 用於GridView控件:

WebForm2.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" %>

<!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 id="Head1" runat="server">
    <title></title>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="Scripts/ScrollableGridPlugin.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#<%=GridView1.ClientID %>').Scrollable({
                ScrollHeight: 100,
                Width: 500
            });
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView runat="server" ID="GridView1" AutoGenerateColumns="false" Width="500px">
            <RowStyle BackColor="#EFF3FB" />
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
            <Columns>                
                <asp:BoundField DataField="AccountNumber" HeaderText="Account Number">                    
                </asp:BoundField>
                <asp:BoundField DataField="AccountName" HeaderText="Account Name">                                    
                </asp:BoundField>
                <asp:BoundField DataField="City" HeaderText="City" >                
                </asp:BoundField>
                <asp:BoundField DataField="Country" HeaderText="Country">                
                </asp:BoundField>
            </Columns>
        </asp:GridView>
    </div>
    </form>
</body>
</html>

 

這裏主要用到了JQuery和ScrollableGridPlugin.js插件。ScrollableGridPlugin.js插件很好用,想要哪個GridView固定住表頭,只需要在開始的Script中加入以下的代碼。第一個參數用來設置表的高度,第二個設置表寬,單位都爲px。這兩個參數也可以省略,ScrollableGridPlugin.js中會設置默認值。

 

1 $(document).ready(function () {
2 $('#<%=GridView1.ClientID %>').Scrollable({
3 ScrollHeight: 100,
4 Width: 500
5 });
6 });

 

ScrollableGridPlugin.js的代碼爲:

(function ($) {
    $.fn.Scrollable = function (options) {
        var defaults = {
            ScrollHeight: 300,
            Width: 0
        };
        var options = $.extend(defaults, options);
        return this.each(function () {
            var grid = $(this).get(0);
            var gridWidth = grid.offsetWidth;
            var gridHeight = grid.offsetHeight;
            var headerCellWidths = new Array();
            for (var i = 0; i < grid.getElementsByTagName("TH").length; i++) {
                headerCellWidths[i] = grid.getElementsByTagName("TH")[i].offsetWidth;
            }
            grid.parentNode.appendChild(document.createElement("div"));
            var parentDiv = grid.parentNode;

            var table = document.createElement("table");
            for (i = 0; i < grid.attributes.length; i++) {
                if (grid.attributes[i].specified && grid.attributes[i].name != "id") {
                    table.setAttribute(grid.attributes[i].name, grid.attributes[i].value);
                }
            }
            table.style.cssText = grid.style.cssText;
            table.style.width = gridWidth + "px";
            table.appendChild(document.createElement("tbody"));
            table.getElementsByTagName("tbody")[0].appendChild(grid.getElementsByTagName("TR")[0]);
            var cells = table.getElementsByTagName("TH");

            var gridRow = grid.getElementsByTagName("TR")[0];
            for (var i = 0; i < cells.length; i++) {
                var width;
                if (headerCellWidths[i] > gridRow.getElementsByTagName("TD")[i].offsetWidth) {
                    width = headerCellWidths[i];
                }
                else {
                    width = gridRow.getElementsByTagName("TD")[i].offsetWidth;
                }
                cells[i].style.width = parseInt(width - 3) + "px";
                gridRow.getElementsByTagName("TD")[i].style.width = parseInt(width - 3) + "px";
            }
            parentDiv.removeChild(grid);

            var dummyHeader = document.createElement("div");
            dummyHeader.appendChild(table);
            parentDiv.appendChild(dummyHeader);
            if (options.Width > 0) {
                gridWidth = options.Width;
            }
            var scrollableDiv = document.createElement("div");
            if (parseInt(gridHeight) > options.ScrollHeight) {
                gridWidth = parseInt(gridWidth) + 17;
            }
            scrollableDiv.style.cssText = "overflow:auto;height:" + options.ScrollHeight + "px;width:" + gridWidth + "px";
            scrollableDiv.appendChild(grid);
            parentDiv.appendChild(scrollableDiv);
        });
    };
})(jQuery);

 

C#的代碼爲:

using System;
using System.Web.UI;
using System.Data;

namespace WebApplication1
{
    public partial class WebForm2 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                DataTable dt = new DataTable();
                dt.Columns.Add(new DataColumn("AccountNumber"));
                dt.Columns.Add(new DataColumn("AccountName"));
                dt.Columns.Add(new DataColumn("City"));
                dt.Columns.Add(new DataColumn("Country"));
                DataRow dr = dt.NewRow();
                dr["AccountName"] = "Test1";
                dr["AccountNumber"] = "001";
                dr["Country"] = "China";
                dr["City"] = "Beijing";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["AccountName"] = "Test2";
                dr["AccountNumber"] = "002";
                dr["Country"] = "China";
                dr["City"] = "Shanghai";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["AccountName"] = "Test3";
                dr["AccountNumber"] = "003";
                dr["Country"] = "the Nederlands";
                dr["City"] = "Amsterdam";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["AccountName"] = "Test4";
                dr["AccountNumber"] = "004";
                dr["Country"] = "France";
                dr["City"] = "Paris";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["AccountName"] = "Test5";
                dr["AccountNumber"] = "005";
                dr["Country"] = "Spain";
                dr["City"] = "Barcelona";
                dt.Rows.Add(dr);
                dr = dt.NewRow();
                dr["AccountName"] = "Test6";
                dr["AccountNumber"] = "006";
                dr["Country"] = "China";
                dr["City"] = "Shanghai";
                dt.Rows.Add(dr);
                GridView1.DataSource = dt;
                GridView1.DataBind();
            }
        }
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章