Thursday, August 23, 2007

add confirmation pop up to a repeaters link button

If you have a repeater that is creating a LinkButtons that you want the users action to be confirmed by a javascript confimation box, you can follow the following scheme:

1.) Create the repeater in the .aspx file and add the LinkButton:
    <asp:Repeater ID="aRepeater" Runat="server" >
  <ItemTemplate>
      <td>
        <#DataBinder.Eval(Container.DataItem, "title")%>
      </td>
  </ItemTemplate>
  <ItemTemplate >
    <asp:LinkButton Runat="server" ID="Btn" CommandArgument=%#DataBinder.Eval (Container.DataItem, "arg")%>
      Text
    </asp:LinkButton>
  </ItemTemplate>
</asp:Repeater>

2.) Add the javascript confirmation in the head that you want the LinkButtons to use:
<script language="javascript">
  function Confirm()
  {
    return confirm("Are you sure?");
  }
</script>

3.) Override the Repeaters ItemCreated event and add the attribute to the LinkButton:
private void Repeater_ItemCreated(object sender, RepeaterItemEventArgs e)
{
  LinkButton btn = e.Item.FindControl("Btn") as LinkButton;
  if (btn != null)
    btn.Attributes["onclick"] = "return Confirm();";
}

4.) Wire-up the delegate in the InitializeComponent section:
this.Repeater.ItemCreated +=new RepeaterItemEventHandler(Repeater_ItemCreated);

That's it.

No comments: