Pergunta

How to count the number of items in a repeater using ASP.NET?

I would like to display something along the lines of:

MARKUP

Page 1 of 5

ASPX

Get Item Index: (working)

<%# DataBinder.Eval(Container, "ItemIndex", "") + 1%>

Count total items: (failing)

<%# DataBinder.Eval(Container.ItemIndex, rpt.Items.Count)%>

I would prefer to do this on page however am open to suggestions and code behind.

Foi útil?

Solução

This is the best solution I get it

<asp:Repeater ID="rptGallery" runat="server"  >
    <ItemTemplate>
        <div>
            <div>        
                <asp:Label ID="Number_of_element_in_repeater" runat="server"
                Text='<%#Convert.ToString(((IList((Repeater)Container.Parent).DataSource).Count) %>'>
                </asp:Label>

            </div>
        </div>
    </ItemTemplate>
</asp:Repeater>

The number of items in repeater is:

Convert.ToString(((IList)((Repeater)Container.Parent).DataSource).Count)

Outras dicas

If the data source is a data table use the below code

<%# Convert.ToString(((System.Data.DataTable)((Repeater)Container.Parent).DataSource).Rows.Count) %>

I believe a SqlDataSource uses a "SQLdatareader", which is one by one row access. So if it has rows, it returns one row at a time, not knowing how much more it has to go.

You could include in your rowset the total amount of rows (something like count(*)), and return that as a field in each row. It's not ideal, but it's one way to return it to your current code.

If you're not opposed to using the codebehind instead\as well, you could call out and fetch the records to get a rowcount that way, and then use that value in your markup (setting it as a hidden field, for example). Either way, you'll need to iterate through all rows before you know how many rows you have.

It looks like you need to cast to a data type that supports the properties you are using, try this:

((Container.Parent as Repeater).DataSource as IList).Count
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top