C# 如何使用参数制作链接按钮onclick

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/775566/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:40:51  来源:igfitidea点击:

How to make a linkbutton onclick with parameters

c#htmlparametersonclicklinkbutton

提问by

HTML :

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
}

回答by Adeel

Use CommandArgument property of linkbutton to pass parameters.

使用链接按钮的 CommandArgument 属性传递参数。

CommandArgument property:

命令参数属性:

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

获取或设置与关联的命令名称属性一起传递给 Command 事件处理程序的可选参数。

LinkButton Members

链接按钮成员

回答by Waleed Eissa

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:

然后处理repeater的ItemCommand事件:

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