Drive:Activated logo
hi there!

I see you've stumbled on to my humble home on the net, Drive:Activated. My name's Sam, I'm an ambitious and driven uni student, residing in Melbourne, Australia, wanting to make my mark on our world. This is my site, which is mainly just my blog and some other bits. There's no definite theme to my blog, just anything that interests me, and currently that's web trends, startups, ideas and cool stuff. Check it out, leave me a comment, click on 'Who is this?' to find out more about me, or drop me a line by clicking on 'Let's Talk'. Hope you enjoy it!

My signature

Content sign

Getting the item number in an asp:Repeater

   Filed under: , , ,    
Warning: this is a nerdy code post, so proceed with caution Wink

While modding my new site in Community Server 2007, I needed to know the item number in the asp:Repeater control so when I reach the last one (the repeater had a fixed number of items) it would not apply a certain CSS class so there isn't a redundant border. I didn't want to inherit the Repeater control and implement the logic in the Render event because I wanted to do it declaratively (because I was lazy basically). It was not immediately obvious as to how, and I still don't know why it is the case, but it works.

First, in the aspx page where the asp:Repeater control lies, add in the following somewhere:
<script language="C#" runat="Server">
//needed as cannot get Container.ItemIndex directly
int GetItemIndex(int index)
{
    return index;
}
</script>
Then inside the ItemTemplate tags of your asp:Repeater control, access the item number (ItemIndex) using the following code:
GetItemIndex(Container.ItemIndex);
You'll have to combine it with something else though because that code above does nothing with the number. Something like this to print it:
<%# GetItemIndex(Container.ItemIndex) %>
Or, this to use it conditionally:
<%# GetItemIndex(Container.ItemIndex) % 2 == 0 ? "print-this-if-true" : "print-this-if-false" %>
There's a ton of things you can do with this code, like create a new table row every 3 items, or make every 5th item red.

Why you can only access Container.ItemIndex when it's wrapped around a method I have no idea, but it didn't work until I did that. There are obviously some intricacies of ASP.NET that my hacking isn't picking up - I've never done ASP.NET coding before, just winforms stuff.

Hope this helps someone hacking through ASP.NET!

Trackbacks sign
No Trackbacks
Trackback URL
No trackbacks yet - link to me people!
Comments sign
1 Comment
Comments RSS RSS icon

Nice ! It Helped me...

I Couldn't remeber the Container keyword...

Tks for your humble post

Pedro Bernardo

http://www.inbox.pt

Post comment sign
Leave a Comment
I know you want to!
(required)  
(optional)
(required)  

Want to keep stay in the loop with the comments here? Leave your email address below and you'll be informed when a new comment is added to this blog post.

(optional):  

Submit