Serenity
Serenity

Reputation: 5098

Adding class to anchor tag inside of repeater in code behind

aspx file

<ul>
                        <asp:Repeater runat="server" ID="rpt1" OnItemDataBound="rpt1_ItemDataBound">
                            <HeaderTemplate>
                                <li><a id="a1" href="javascript:void(0);" runat="server">Text</a></li>
                            </HeaderTemplate>
                            <ItemTemplate>
                                <li><a id="name" runat="server" href="javascript:void(0);">
                                    <%# Eval("Name").ToString() %></a>
                                    <asp:Label runat="server" ID="lblID" Visible="false" Text='<%#Eval("ID") %>'></asp:Label>
                        </li>
                            </ItemTemplate>
                        </asp:Repeater>
                    </ul>

Now there are five items in the ItemTemplate of this repeater..what i want is to set class of each of the anchor tags as "mySprite id1,mySprite id2 , mySprite id3 and so on.."

for that I did this in code behind...

for (int i = 1; i < 6; i++)
                {
                    Name.Attributes.Add("class", "sprite id" + i);
                }

Now when I view page source, ALL my anchor tags have got class set as class="sprite id5"

what am I doing wrong ? Plz help..thnx

Upvotes: 2

Views: 8666

Answers (2)

Carson63000
Carson63000

Reputation: 4232

Try something like this in your OnItemDataBound event handler:

protected void rpt1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
    {
        HtmlAnchor nameAnchor = (HtmlAnchor)e.Item.FindControl("name");
        nameAnchor.Attributes.Add("class", "sprite id" + (e.Item.ItemIndex + 1));
    }
}

Upvotes: 2

JohnB
JohnB

Reputation: 18992

At the end of the for loop, Name has the value "id5". The for loop in code behind is evaluated first, then the end result value of "id5" is bound to the repeater (5 times).

Since the <asp:Repeater> is designed to display data from a DataSource, you could add the class names "id1, id2, id3, id4, id5, etc." to each row of your data, and bind that field to the class name.

Or, unless you are using GUIDs, you can Concat() the id field of the table to "id"

Upvotes: 1

Related Questions