关于DataGrid等控件中的自动编号
论坛中有很多人问关于DataGrid的自动编号问题,但在论坛中我已经回复过好几次,但还是不断有人问
| 
 序号  | 
 内容  | 
| 
 1  | 
 Taye  | 
| 
 2  | 
 BOx  | 
| 
 3  | 
 Glass  | 
| 
 4  | 
 StarCraft  | 
一、正序
A、AllowPaging=False情况下
| 
 <asp:DataGrid id="DataGrid1" runat="server">  | 
就可以实现
不过更有趣的方法是使用这个方法
| 
  <asp:DataGrid id="DataGrid1" runat="server">  | 
也许有些人会觉得很奇怪为什么Items.Count会这样,而不是出来全部总合..但如果你了解绑定的过程时就容易理解.
[从上面来看就是在ItemCreated事件中进行绑定所以得到的Items.Count刚好是当前的序号]
B、AllowPaging="True"下 
如果你DataGrid支持分页则可以如下
| 
 <asp:DataGrid id="DataGrid1" runat="server" AllowPaging="True">  | 
二、倒序的方法 
| 
 序号  | 
 内容  | 
| 
 4  | 
 Taye  | 
| 
 3  | 
 BOx  | 
| 
 2  | 
 Glass  | 
| 
 1  | 
 StarCraft  | 
由上面可以知道使用
this.DataGrid1.Items.Count - Container.ItemIndex + 1方法是不可能实现的,得到值而且全会为1
分页的情况下更是一样.所以一开始我们就要取得数据源的行数 
| 
 .cs  | 
| 
              private int rowscount = 0;          protected int RowsCount          {               get{ return rowscount;}               set{ this.rowscount = value; }          }                private void Page_Load(object sender, System.EventArgs e)          {               // 在此处放置用户代码以初始化页面               if(!IsPostBack)                    this.BindData();          }          private void BindData()          {               SqlConnection cn = new SqlConnection("server=(local);database=NorthWind;uid=sa;pwd=");               string str=@"SELECT Employees.EmployeeID, Orders.EmployeeID                                  FROM Employees INNER JOIN                        Orders ON Employees.EmployeeID = Orders.EmployeeID ";               SqlDataAdapter sqlda = new SqlDataAdapter(str,cn);               DataSet ds = new DataSet();               sqlda.Fill(ds);               this.RowsCount = ds.Tables[0].Rows.Count;               this.DataGrid1.DataSource = ds;               this.DataGrid1.DataBind();          }  | 
| 
 .aspx  | 
| 
 <asp:DataGrid id="DataGrid1" runat="server" AllowPaging="True">                             <Columns>                                    <asp:TemplateColumn>                                           <ItemTemplate>                                                  <%# RowsCount - DataGrid1.CurrentPageIndex * DataGrid1.PageSize - Container.ItemIndex %>                                           </ItemTemplate>                                    </asp:TemplateColumn>                             </Columns>                      </asp:DataGrid>  | 
http://mblogger.cn/taye/posts/21240.aspx
posted on 2004-07-09 09:02 HelloSnoopy 阅读(533) 评论(0) 收藏 举报
                    
                
                
            
        
浙公网安备 33010602011771号