简体   繁体   English

将值从GridView传递到ASP.NET中文件后面的代码

[英]Passing values from GridView to code behind file in ASP.NET

I have a GridView that binds values from the database. 我有一个GridView绑定数据库中的值。 Here is the code: 这是代码:

<asp:GridView ID="GridView1" AutoGenerateColumns="False" DataKeyNames="DataView" runat="server" OnRowCommand="GridView1_RowCommand">
            <Columns>
                <asp:BoundField  DataField="ProductName" HeaderText="Title" />
                <asp:ImageField DataImageUrlField="ProductId" DataImageUrlFormatString="getProductImage.ashx?ProductID={0}" HeaderText="Image">
                </asp:ImageField>
                <asp:BoundField DataField="ProductDescription" HeaderText="Description" />
                <asp:BoundField DataField="ProductCost" HeaderText="Cost" />
             <asp:TemplateField HeaderText="Quantity">
                 <ItemTemplate>
                     <asp:TextBox runat="server" TextMode="Number" ID="txtQuantity"></asp:TextBox>
                 </ItemTemplate>
             </asp:TemplateField>
                <asp:ButtonField Text="Button" CommandName="AddToCart" />
            </Columns>
        </asp:GridView>

I want to pass the command arguments containing values from txtQuantity and ProductID to the code behind on CommandName "AddToCart". 我想将包含txtQuantity和ProductID值的命令参数传递给CommandName“ AddToCart”后面的代码。 How can I do this? 我怎样才能做到这一点?

Bind the values of the ProductID & Quantity in the GridView. 在GridView中绑定ProductID和Quantity的值。 In GridView, give like this: 在GridView中,如下所示:

<asp:GridView ID="GridView1" AutoGenerateColumns="False" DataKeyNames="DataView" runat="server" OnRowCommand="GridView1_RowCommand">
        <Columns>
            <asp:BoundField  DataField="ProductName" HeaderText="Title" />
            <asp:ImageField DataImageUrlField="ProductId" DataImageUrlFormatString="getProductImage.ashx?ProductID={0}" HeaderText="Image">
            </asp:ImageField>
            <asp:BoundField DataField="ProductDescription" HeaderText="Description" />
            <asp:BoundField DataField="ProductCost" HeaderText="Cost" />
         <asp:TemplateField HeaderText="Quantity">
             <ItemTemplate>
                 <asp:TextBox runat="server" TextMode="Number" ID="txtQuantity" Text="<%# Bind("Quantity")%>"></asp:TextBox>
             </ItemTemplate>
         </asp:TemplateField>
            <asp:Button Text="Button" CommandName="AddToCart" CommandArgument="<%# Eval("Quantity") + "," + Eval("ProductID")%>"  />
        </Columns>
    </asp:GridView>

In GridView RowCommand event, give the below code: 在GridView RowCommand事件中,提供以下代码:

  if(e.CommandName == "AddToCart")
  {
      string[] args = e.CommandArgument.ToString().Split(",");
      Decimal Quantity = Convert.ToDecimal(args[0]);
      int ProductID = Convert.ToInt32(args[1]);          
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM