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

时间:2014-04-07 06:48:40

标签: c# asp.net gridview

我有一个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"></asp:TextBox>
                 </ItemTemplate>
             </asp:TemplateField>
                <asp:ButtonField Text="Button" CommandName="AddToCart" />
            </Columns>
        </asp:GridView>

我想将包含来自txtQuantity和ProductID的值的命令参数传递给CommandName&#34; AddToCart&#34;后面的代码。 我怎么能这样做?

1 个答案:

答案 0 :(得分:0)

绑定ProductID&amp;的值。 GridView中的数量。在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>

在GridView RowCommand事件中,提供以下代码:

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