How to make a linkbutton onclick with parameters

AndyC picture AndyC · Apr 22, 2009 · Viewed 25.6k times · Source

HTML :

<asp:LinkButton ID="lnk_productImage" runat="server" Text="select"
   OnClick="viewProductImage('<%#DataBinder.Eval(Container.DataItem,"Id") %>')"
   >
</asp:LinkButton>

CodeBehind:

protected void viewProductImage(object sender, EventArgs e, int id)
{ 
    //Load Product Image
}

Answer

Waleed Eissa picture Waleed Eissa · Apr 22, 2009

I see you're using a repeater, so you probably could use this code:

In your repeater template:

<asp:Repeater ID="_postsRepeater" runat="server" OnItemCommand="_postsRepeater_ItemCommand">
  <ItemTemplate><asp:LinkButton ID="_postDeleteLinkButton" runat="server" CommandName="DeletePost" CommandArgument="<%# ((Post)Container.DataItem).ID %>">Delete</asp:LinkButton></ItemTemplate>
</asp:Repeater>

Then handle the repeater's ItemCommand event:

protected void _postsRepeater_ItemCommand(object source, RepeaterCommandEventArgs e)
{
    if (e.CommandName == "DeletePost") // Replace DeletePost with the name of your command
    {
        // Get the passed parameter from e.CommandArgument
        // e.g. if passed an int use:
        // int id = Convert.ToInt32(e.CommandArgument);
    }
}