如何在渲染时在C#ASP.NET ListView中获取当前记录的索引
我有一个列表视图如下:
{itemdata}
我想用一个正在运行的计数器替换{recordNumber}
,所以显示的第一个记录为1,第二个记录为2,依此类推。
我怎样才能做到这一点?
提前致谢
如果ID不是来自例如数据库,则可以使用Container.DisplayIndex
或Container.DataItemIndex
来执行此操作。
关键是: class="Amazing-<%#Container.DisplayIndex + 1 %>"
。
如果recordNumber
确实来自外部数据源,您可以这样做: class='Amazing-<%# Eval("YourDatabaseIDColumn") %>'
。
如果要分页数据源,DisplayIndex和DataItemIndex会有所不同。 DisplayIndex是一个始终在当前页面上开始的运行索引,DataItemIndex是整个数据源中的运行数字。
这是一个例子:
代码隐藏:
//just to represent something like a db table with an ID and a description Pair[] data = new Pair[] { new Pair(123, "row1"), new Pair(124, "row2"), new Pair(125, "row3"), new Pair(126, "row4"), new Pair(127, "row5"), new Pair(128, "row6"), new Pair(129, "row7"), new Pair(130, "row8"), new Pair(131, "row9"), new Pair(132, "row10") }; lstTopRanks.DataSource = data; lstTopRanks.DataBind();
ASPX:
DisplayIndex: <%#Container.DisplayIndex %>; DataItemIndex: <%#Container.DataItemIndex %>, ID and Text: <%#((Pair)Container.DataItem).First %>, <%#((Pair)Container.DataItem).Second %>