How to prevent duplicate content in an element template for an alternating template in a repeater?

Is there a way to prevent duplicate content of an itemtemplate that will only display with a different css class for an alternating template block?

<asp:Repeater ID="rptCommentHistory" runat="server"> <ItemTemplate> <asp:Label ID="lblComment" runat="server" Text='<%#Eval("Comment").ToString() %>' Class="itemTemplate"/> </ItemTemplate> <AlternatingItemTemplate> <asp:Label ID="lblComment" runat="server" Text='<%#Eval("Comment").ToString() %>' Class="alternatingTtemTemplate"/> </AlternatingItemTemplate> </asp:Repeater> 
+4
source share
4 answers

This should do what you want :-)

 <asp:Repeater ID="rptData" runat="server"> <ItemTemplate> <asp:Label ID="lblData" runat="server" Text='<%# Eval("Comments") %>' CssClass='<%# Container.ItemIndex%2==0?"itemTemplate":"alternatingTtemTemplate" %>'></asp:Label> </ItemTemplate> </asp:Repeater> 
+4
source

I never use AlternatingItemTemplate . I don’t like duplicating my code in order to have a variable element, and I think that if the code is different from the fact that it cannot be classified as duplicate, then you should not use the Repeater control in any case.

Therefore, I always use an ItemTemplate and make the necessary changes to the ItemDataBound event.

To determine if an element is a normal or variable element, I would do something like:

 if ((e.Item.ItemIndex+1 % 2)=0){ //Alternating code here.. } 

In your case, the only difference is the change in Label CssClass , so I would do something like:

 if ((e.Item.ItemIndex+1 % 2)=0){ Label lblComment = e.Item.FindControl("lblComment"); lblComment.CssClass = "alternatingTtemTemplate"; } 
+2
source

This is not exactly duplication as such, do not worry about it. You implement this to a large extent, as intended.

The only other option I can think of is to use the itemmemplate element, write code that fires on the itemdatabound event and programmatically change the css class using FindControl.

I know that I prefer to use ...

0
source

It seems that the proposed solutions do not satisfy and that there is no other ".net" solution, I would suggest that you do this in javascript (since it is not in pure CSS).

jQuery allows you to apply a different style to even and random selector elements. It should work with elements other than table rows ...

So something like this should work:

 $("#rptCommentHistory span:even").addClass("itemTemplate"); $("#rptCommentHistory span:odd").addClass("alternatingTtemTemplate"); 

Or you can simply set the ItemTemplate for all items and use (it might work better):

 $("#rptCommentHistory span:odd").removeClass("ItemTemplate").addClass("alternatingTtemTemplate"); 
0
source

All Articles