ASP.net C # Gridview ButtonField onclick event

I wrote ASP code for an online store type project. There is a method that adds ProductID to the cookie and adds 1 to the quantity of the product. Another method reads the cookie, converts the cookie into a data table and puts it in a gridview. This gridview is basically a page of shoppingcart.aspx.

Now I need a way to add a button field to this gridview, where I can add a ++ button (for example, the add button to the shopping cart on the product page), ordinary asp buttons accept onclick="methodname" , but not in gridview.

 add1ToShoppingCart(string productId) {[...]shoppingCartCookie[productId] = (amount + 1).ToString();} 

This is the code that I use for all ++ buttons. It accepts the button button.id (buttonID = productID). Therefore, I need all the buttons to be the same image, but the buttonID must be attached to the productID so that it can somehow execute this method (with some kind of onclick="" ).

I have looked and google for the last couple of hours, but I can’t find anything. In the past, I found many answers on stackoverflow, so I was hoping someone here could help.

Thanks in advance.

+1
source share
1 answer

you can use the 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, the following event of your gridview is created for you and do what you want:

  protected void GV_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "AddToCard") { //Write code to add to card } } 

GV is the identifier of my GridView!

+8
source

Source: https://habr.com/ru/post/1208825/


All Articles