Friday, May 8, 2009

Add client on click to asp repeater

To add a client side onclick event to buttons in a repeater, use the scenario below as a reference.


Within the web form:
<asp:Repeater ID="ItemsRpt" Runat="server">
  <ItemTemplate>
    <tr>
      <td><%#DataBinder.Eval(Container.DataItem, "ItemName")%></td>
      <td>
        <asp:Button ID="DeleteBtn" Runat="server" Visible=<%#System.Convert.ToBoolean(DataBinder.Eval(Container.DataItem, "canDelete"))%> Text="Delete" CommandArgument=<%#DataBinder.Eval(Container.DataItem, "ItemId")%> CommandName="DeleteItem" CssClass="Btn" CausesValidation="False"></asp:Button>
      </td>
    </tr>
  </ItemTemplate>
</asp:Repeater>

Within the code behind "InitializeComponent"
this.ItemsRpt.ItemCreated += new RepeaterItemEventHandler(ItemsRpt_ItemCreated);

and then...
private void PositionsRpt_ItemCreated(object sender, RepeaterItemEventArgs e)
{
  if (e.Item.DataItem != null)
  {
    Button btn = e.Item.FindControl("DeleteBtn") as Button;
    if (btn != null) {
      btn.Attributes.Add("onclick", "return confirm('Confirm the deletion of this item');");
    }
  }
}

No comments: