关于datagrid控件中的自动编号
一、正序
a、allowpaging=false情况下
<asp:datagrid id="datagrid1" runat="server">
<columns>
<asp:templatecolumn>
<itemtemplate>
<%# container.itemindex + 1%>
</itemtemplate>
</asp:templatecolumn>
</columns>
</asp:datagrid>
就可以实现,不过更有趣的方法是使用这个方法
<asp:datagrid id="datagrid1" runat="server">
<columns>
<asp:templatecolumn>
<itemtemplate>
<%# this.datagrid1.items.count + 1%>
</itemtemplate>
</asp:templatecolumn>
</columns>
</asp:datagrid>
也许有些人会觉得很奇怪为什么items.count会这样,而不是出来全部总合..但如果你了解绑定的过程时就容易理解.
[从上面来看就是在itemcreated事件中进行绑定所以得到的items.count刚好是当前的序号]
b、allowpaging="true"下
如果你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>
二、倒序的方法
序号 内容
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>
trackback: http://tb.blog.csdn.net/trackback.aspx?postid=1487362