為GridView添加序號列,且支持分頁連續累計顯示,廢話不多說,直接上代碼:
<%@ 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></head><body> <form id="form1" runat="server"> <div> <asp:GridView ID="GridView1" runat="server" AllowPaging="True" AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="id" DataSourceID="SqlDataSource1" Width="100%" PageSize="5"> <Columns> <asp:TemplateField HeaderText="序號"> <ItemTemplate> <asp:Literal ID="Literal1" runat="server" Text='<%# (Container.DataItemIndex+1) %>'></asp:Literal> </ItemTemplate> <ItemStyle BackColor="#FFFFCC" Font-Bold="True" ForeColor="#FF3300" Width="80px" /> </asp:TemplateField> <asp:BoundField DataField="id" HeaderText="id" ReadOnly="True" SortEx簡要說明一下,由于我這里是作演示,所以我直接采用數據源SqlDataSource,大家仁者見仁,智者見智吧,實現自動生成序號的方法很多,最常見的是通過添加GridView1_RowDataBound方法,然后在里面依據實際情況計算序號,我這人希望能越簡單且越好用就最好了,所以我采用了上面的方法,核心代碼是:(Container.DataItemIndex+1),其中Container.DataItemIndex表示當前行索引,由于索引是從0開始,所以加上1就OK了,這樣整個表就有序號了,而且在分頁下也是連續性的,不會出現每頁從1開始的情況。
效果如下:
另外需要說明的是,如果大家不是采用數據源控件,而是自己手動去綁定數據源的情況,那就不能簡單按照方面的方法,原因是Container.DataItemIndex在手動綁定數據源時,會索引并不會記住,每次綁定均會重新從0開始,所以這時候我們需要按照當前的頁碼來進行計算,代碼也很簡單,如下:
<asp:TemplateField HeaderText="序號"> <ItemTemplate> <asp:Literal ID="Literal1" runat="server" Text='<%# ((GridView1.PageSize * GridView1.PageIndex) + Container.DataItemIndex +1) %>'></asp:Literal> </ItemTemplate> <ItemStyle BackColor="#FFFFCC" Font-Bold="True" ForeColor="#FF3300" Width="80px" /> </asp:TemplateField>更多IT相關的文章,歡迎光臨我的個人網站:http://www.zuowenjun.cn/
新聞熱點
疑難解答