开发者

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


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));
    }
}


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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜