為GridView添加序號(hào)列,且支持分頁(yè)連續(xù)累計(jì)顯示,廢話不多說(shuō),直接上代碼:
<%@ 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="序號(hào)"> <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簡(jiǎn)要說(shuō)明一下,由于我這里是作演示,所以我直接采用數(shù)據(jù)源SqlDataSource,大家仁者見(jiàn)仁,智者見(jiàn)智吧,實(shí)現(xiàn)自動(dòng)生成序號(hào)的方法很多,最常見(jiàn)的是通過(guò)添加GridView1_RowDataBound方法,然后在里面依據(jù)實(shí)際情況計(jì)算序號(hào),我這人希望能越簡(jiǎn)單且越好用就最好了,所以我采用了上面的方法,核心代碼是:(Container.DataItemIndex+1),其中Container.DataItemIndex表示當(dāng)前行索引,由于索引是從0開(kāi)始,所以加上1就OK了,這樣整個(gè)表就有序號(hào)了,而且在分頁(yè)下也是連續(xù)性的,不會(huì)出現(xiàn)每頁(yè)從1開(kāi)始的情況。
效果如下:
另外需要說(shuō)明的是,如果大家不是采用數(shù)據(jù)源控件,而是自己手動(dòng)去綁定數(shù)據(jù)源的情況,那就不能簡(jiǎn)單按照方面的方法,原因是Container.DataItemIndex在手動(dòng)綁定數(shù)據(jù)源時(shí),會(huì)索引并不會(huì)記住,每次綁定均會(huì)重新從0開(kāi)始,所以這時(shí)候我們需要按照當(dāng)前的頁(yè)碼來(lái)進(jìn)行計(jì)算,代碼也很簡(jiǎn)單,如下:
<asp:TemplateField HeaderText="序號(hào)"> <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相關(guān)的文章,歡迎光臨我的個(gè)人網(wǎng)站:http://www.zuowenjun.cn/
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注