How to add an attribute to repeater item at runtim

2019-07-24 19:01发布

问题:

I have a repeater and i want to add a mouse over attribute to its items.

Is it possible to add attributes at run-time, if yes then how?

回答1:

Markup:

<asp:Repeater ID="Repeater1" runat="server" OnItemDataBound="Repeater1_ItemDataBound">
     <HeaderTemplate>
          <table>
     </HeaderTemplate>
     <ItemTemplate>
          <tr runat="server" id="itemRow">
               <td>
                    <%# Container.DataItem.ToString() %>
               </td>
          </tr>
     </ItemTemplate>
     <FooterTemplate>
          </table>
     </FooterTemplate>
</asp:Repeater>

Code:

protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
    var row = e.Item.FindControl("itemRow") as HtmlTableRow;
    if (row != null)
    {
        row.Attributes["onmouseover"] = string.Format("alert('Hello from row #{0}');", e.Item.ItemIndex );
    }
}