How to get index of current records in C # ASP.NET ListView in Render Time
I have a list as below:
<asp:ListView ID="lstTopRanks" runat="server"> <ItemTemplate> <div class="Amazing-{recordNumber}">{itemdata}</div> </ItemTemplate> </asp:ListView> I would like to replace {recordNumber} with a work counter, so the first record shown is 1, the second will be 2, etc.
How can i do this?
Thanks in advance
You can do this using Container.DisplayIndex or Container.DataItemIndex if the identifier does not come from, for example, a database.
Key: class="Amazing-<%#Container.DisplayIndex + 1 %>" .
If recordNumber comes from an external data source, you can do it the same way: class='Amazing-<%# Eval("YourDatabaseIDColumn") %>' .
DisplayIndex and DataItemIndex are different if you dig your data source. DisplayIndex is a running index, always starting from the current page, and DataItemIndex is the running number in your full data source.
Here is an example:
CodeBehind:
//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:
<asp:ListView ID="lstTopRanks" runat="server"> <LayoutTemplate><asp:PlaceHolder ID="ItemPlaceHolder" runat="server"></asp:PlaceHolder></LayoutTemplate> <ItemTemplate> <div class="Amazing-<%#Container.DisplayIndex + 1 %>"> DisplayIndex: <b><%#Container.DisplayIndex %></b>; DataItemIndex: <b><%#Container.DataItemIndex %></b>, ID and Text: <i><%#((Pair)Container.DataItem).First %>, <%#((Pair)Container.DataItem).Second %></i> </div> </ItemTemplate> </asp:ListView> <asp:DataPager ID="DataPagerProducts" runat="server" PagedControlID="lstTopRanks" PageSize="3" > <Fields> <asp:NextPreviousPagerField ShowFirstPageButton="True" ShowNextPageButton="False" /> <asp:NumericPagerField /> <asp:NextPreviousPagerField ShowLastPageButton="True" ShowPreviousPageButton="False" /> </Fields> </asp:DataPager> And the result:
