How to make a linkbutton onclick with parameters

2019-07-12 02:34发布

问题:

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
}

回答1:

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


回答2:

Use CommandArgument property of linkbutton to pass parameters.

CommandArgument property:

Gets or sets an optional argument passed to the Command event handler along with the associated command name property.

LinkButton Members