如何对GridView行自动编号?

有时候会遇到这样的情况,就是需要对GridView表格显示的结果增加一列自动递增编号列,以标示每一行的序号。要实现这一功能,首先在 GridView 第一列加入一个 TemplateField,并在 TemplateField 的 ItemTemplate 加入一个 Label (ID=lblNo),*.aspx 对应代码如下:

< asp:GridView  ID ="GridView1"  runat ="server"  AllowPaging ="True"  AutoGenerateColumns ="False"   
    DataKeyNames
="Flag,ID"  DataSourceID ="SqlDataSource1"  EmptyDataText ="无记录。" >    
    
< Columns >    
        
< asp:TemplateField  HeaderText ="编号" >    
            
< ItemTemplate >    
                
< asp:Label  ID ="lblNo"  runat ="server"  Text ="Label" ></ asp:Label >    
            
</ ItemTemplate >    
            
< ItemStyle  Wrap ="True"   />    
            
< HeaderStyle  Wrap ="False"   />    
        
</ asp:TemplateField >    
    
</ Columns >    
</ asp:GridView >  

然后在 GridView 的 RowDataBound 事件中,设定每一列的 lblNo 的 Text 属性值为 RowIndex + 1(因为 RowIndex 起始编号为 0 ,所以每一行的自动编号为 RowIndex + 1) 。

protected   void  GridView1_RowDataBound( object  sender, GridViewRowEventArgs e)
    {
        Label olabel;
        
if  (e.Row.RowType  ==  DataControlRowType.DataRow)
        {
            olabel 
=  (Label)e.Row.Cells[ 0 ].FindControl( " lblNo " );
            olabel.Text 
=  Convert.ToString(e.Row.RowIndex  +   1 );
        }
    }

如果遇到有分页时,以上代码对每一页都是从1开始编号,所以对于有分页的情况需要修改成:
protected   void  GridView1_RowDataBound( object  sender, GridViewRowEventArgs e)
    {
        Label olabel;
        
if  (e.Row.RowType  ==  DataControlRowType.DataRow)
        {
            olabel 
=  (Label)e.Row.Cells[ 0 ].FindControl( " lblNo " );
            olabel.Text 
=  Convert.ToString(GridView1.PageIndex  *  GridView1.PageSize  +  e.Row.RowIndex  +   1 );
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值