zoukankan      html  css  js  c++  java
  • 如何对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);
            }
        }
  • 相关阅读:
    VMWare ESX Server
    ubuntu 13.04 xrdp 远程桌面连接问题[转载]
    wget 使用技巧
    C# 跨线程调用问题
    ASP.NET WEB API 返回JSON 出现2个双引号问题
    ASP.NET MVC 4 中Razor 视图中JS无法调试
    Android 如何修改gen下包的名字
    打开AVD时报”Data partition already in use. Changes will not persist!”
    Android 将APK文件安装到AVD中并分析其界面结构
    Android 实现界面(Activity)的跳转
  • 原文地址:https://www.cnblogs.com/top5/p/1868122.html
Copyright © 2011-2022 走看看