C# – ASP.net C# Gridview ButtonField onclick event

asp.netcdata-bindingonclick

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.

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.

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="").

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.

Thanks in advance.

Best Answer

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 :

 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 !

Related Topic