[Asp.Net]GridView序号

本文介绍了在ASP.NET中为GridView控件添加自动序号的方法,包括后台和前台实现方式,并针对分页情况提供了具体的实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GridView控件中加自动序号,有多种实现方法,你只需要根据的实用要求来确定。总的来分为后台写法和前台写法,后台写法一般不考虑分页的情况下使用,原理就是在GridView 绑定数据时,在RowDataBound 事件中来处理。

页面的列为:

<asp:BoundField  HeaderText="序号" />

或用

<asp:TemplateField HeaderText="序号"> 
<ItemTemplate> 
</ItemTemplate> 
</asp:TemplateField> 

CS代码为:

protected void GridView1_RowDataBond(object sender, GridViewRowEventArgs e)
{
         if (e.Row.RowIndex >= 0)
         {
          e.Row.Cells[0].Text = Convert.ToString(e.Row.RowIndex + 1);
         }           
   }

页面直接实现比如直观,知道Container.DataItemIndex 属性的含义就行:

<asp:TemplateField HeaderText="序号"> 
<ItemTemplate> 
   <%# Container.DataItemIndex + 1%> 
 </ItemTemplate> 
</asp:TemplateField>

下面考虑的主要是分页情况下的,在ASP.NET中分页方法一般用GridView自带的分页工具和AspNetPager的比较多。GridView自带的分页写法

<asp:TemplateField HeaderText="序号"> 
<ItemTemplate> 
<%# this.GridView1.PageIndex  * this.GridView1.PageSize 

         + GridView1.Rows.Count + 1%> 
</ItemTemplate> 
</asp:TemplateField> 

AspNetPager分页情况下的写法为

<asp:TemplateField HeaderText="序号"> 
<ItemTemplate> 
   <%# (this.Pager1.CurrentPageIndex - 1) * this.Pager1.PageSize 

    + Container.DataItemIndex + 1%> 
</ItemTemplate> 
</asp:TemplateField> 




 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

厦门德仔

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值