ASP.net C# Gridview ButtonField onclick event

好久不见. 提交于 2019-12-11 06:56:33

问题


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.


回答1:


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 !



来源:https://stackoverflow.com/questions/10970501/asp-net-c-sharp-gridview-buttonfield-onclick-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!