ASP.net C# Gridview ButtonField onclick 事件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10970501/
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
ASP.net C# Gridview ButtonField onclick event
提问by broodrooster
I've written an ASP code for a webshop type project. There is a method that adds the ProductID to a cookie and adds 1 to the quantity of the product. Another method reads the cookie, transforms the cookie to a data table and puts it in a gridview. This gridview basically is the shoppingcart.aspx page.
我为网店类型的项目编写了 ASP 代码。有一种方法可以将 ProductID 添加到 cookie 并在产品数量上加 1。另一种方法读取 cookie,将 cookie 转换为数据表并将其放入 gridview。这个gridview 基本上是shoppingcart.aspx 页面。
What i now need is a way to add a buttonfield to that gridview where i can add a ++ button (like the add to shopping cart button on a product page), normal asp buttons take a onclick="methodname"but these in the gridview don't.
我现在需要的是一种向该网格视图添加按钮字段的方法,我可以在其中添加 ++ 按钮(例如产品页面上的添加到购物车按钮),普通的 asp 按钮需要一个,onclick="methodname"但这些在 gridview 中没有。
add1ToShoppingCart(string productId)
{[...]shoppingCartCookie[productId] = (amount + 1).ToString();}
That is the code I use for all the ++ buttons. It takes the button.id (buttonID=productID). So I need a way to have all the buttons be the same image, but the buttonID has to be databound to the productID so it can somehow execute that method (with some sort of onclick="").
这是我用于所有 ++ 按钮的代码。它需要 button.id (buttonID=productID)。所以我需要一种方法让所有按钮都是相同的图像,但 buttonID 必须数据绑定到 productID 以便它可以以某种方式执行该方法(使用某种onclick="")。
I've looked and googled for the past couple hours but I cant seem to find anything. In the past I found a lot of answers on stackoverflow so I hoped somebody here could help.
在过去的几个小时里,我一直在寻找和谷歌搜索,但我似乎找不到任何东西。过去我在stackoverflow上找到了很多答案,所以我希望这里有人可以提供帮助。
Thanks in advance.
提前致谢。
采纳答案by Karamafrooz
you can use Template field :
您可以使用模板字段:
<asp:TemplateField ItemStyle-Width="33px" ItemStyle-HorizontalAlign="Center" ItemStyle-VerticalAlign="Middle"
ShowHeader="false" HeaderStyle-Height="40px">
<ItemTemplate>
<asp:ImageButton ID="btnAddToCard" runat="server" ImageUrl="~/Images/btnAddToCard.png" CausesValidation="false"
CommandName="AddToCard" CommandArgument='<%# Eval("ID") %>'
/>
</ItemTemplate>
<HeaderStyle Height="40px"></HeaderStyle>
<ItemStyle HorizontalAlign="Center" VerticalAlign="Middle" Width="33px"></ItemStyle>
</asp:TemplateField>
and in your C# code behind you create the following event of your gridview and do what you want :
并在您背后的 C# 代码中创建 gridview 的以下事件并执行您想要的操作:
protected void GV_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "AddToCard")
{
//Write code to add to card
}
}
GV is the ID of my GridView !
GV 是我的 GridView 的 ID!

