给DataGrid添加自动增长的序列号

这里提供几个简单好用的方法

原理:给数据源添加一个序列

代码如下:
//获得数据源
    mySelectCommand = "select * from table" ;

    SqlDataAdapter myCommand
= new SqlDataAdapter(mySelectCommand,myConnection);

    DataTable dt
= new DataTable();
    myCommand.Fill(dt);    
//将数据库获得的结果集付给dt,以进一步操作
//给dt加序列
    dt.Columns.Add("index",typeof(int));//加序列
   int index;
   
for( index = 0; index < dt.Rows.Count; index ++)
  
{
     dt.Rows[index][
"index"] = index+1; //加序号
   }

//绑定数据源
    myDataGrid.DataSource = dt.DefaultView ;
    myDataGrid.DataBind();


以上从数据源的角度来解决这个问题。
其实从DataGrid本身就可以很好地解决这个问题。比起上面的方法自然好很多。

原理:
1。利用该DataGrid的Container.ItemIndex


<asp:DataGrid id="DataGrid1" runat="server">
    
<Columns>
     
<asp:TemplateColumn>
      
<ItemTemplate>
       
<%# Container.ItemIndex + 1%>
      
</ItemTemplate>
     
</asp:TemplateColumn>
    
</Columns>
</asp:DataGrid>

这种方法再简单不过了,不过无法应用在分页的情况下。

2。利用DataGrid自身加载过程中.Items.Count的属性来实现


<asp:DataGrid id="DataGrid1" runat="server">
    
<Columns>
     
<asp:TemplateColumn>
      
<ItemTemplate>
       
<%# this.DataGrid1.Items.Count + 1%>
      
</ItemTemplate>
     
</asp:TemplateColumn>
    
</Columns>
</asp:DataGrid>

分页情况下,代码如下:


<asp:DataGrid id="DataGrid1" runat="server" AllowPaging="True">
    
<Columns>
    
<asp:TemplateColumn>
      
<ItemTemplate>
      
<%# this.DataGrid1.CurrentPageIndex * this.DataGrid1.PageSize + Container.ItemIndex + 1%>
      
</ItemTemplate>
     
</asp:TemplateColumn>
    
</Columns>
</asp:DataGrid>

作者:BuildNewApp
出处:http://syxchina.cnblogs.comBuildNewApp.com
本文版权归作者、博客园和百度空间共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则作者会诅咒你的。
如果您阅读了我的文章并觉得有价值请点击此处,谢谢您的肯定1。
原文地址:https://www.cnblogs.com/syxchina/p/2197350.html