代码之家  ›  专栏  ›  技术社区  ›  IrishChieftain

GridView模板-如何从所选行中获取数据

  •  2
  • IrishChieftain  · 技术社区  · 15 年前
    <asp:TemplateField>    
        <ItemTemplate>
            <table width="540" cellpadding="5">
            <tr>
                <td align="left" style="width:60%;">
                    <img src='PurchaseHandler.ashx?ProductID=<%# Eval("ProductID")%>' 
                        alt="<%# Eval("ProductName") %>" />
                </td>
                <td align="left">
                     <h3 style="text-align:left;">
                         <asp:Label ID="nameLabel" runat="server" 
                             Text='<%# Eval("ProductName") %>'  />
                     </h3>
                     <asp:Label ID="priceLabel" runat="server" Text='<%# Eval("Price") %>' />  
                     <br />
                     <asp:LinkButton ID="cartLink" runat="server" Text="<b>Add to Cart</b>"
                         CommandName="Add" CommandArgument='<%# Eval("ProductID") %>' />
                </td>
            </tr>
            </table>
        </ItemTemplate>
    </asp:TemplateField>
    

    我正在使用购物车业务对象,该对象包含不用于在GridView中显示的字段。我在rowcommand事件处理程序中接下来要做的是从所选行中检索其余的数据字段。这将为我提供所选行中正确的产品ID:

    if (e.CommandName == "Add")
    {
        int productID = 0;
        int.TryParse(e.CommandArgument as string, out productID);
    
        // Big blank!
    }
    

    如何从所选行中获取其余数据字段以填充购物车?通过解释,我可能可以使用productID挖掘从会话状态提取的数据集,并以这种方式获取数据。但是,我要确定的是,在这种情况下是否有类似于此的语法可以使用?

    DataRow[] rows = ds.Tables[0].Select("ProductID=" +
                         gridProducts.SelectedDataKey.Values["ProductID"].ToString());
    DataRow row = rows[0];
    
    1 回复  |  直到 15 年前
        1
  •  5
  •   David Hall    15 年前

    这样做的一种方法是使用命令参数来存储行索引(可能将其设置在“在行创建”事件中)。

    然后您可以使用下面的代码访问您的行(代码截取自 MSDN ):

      // Convert the row index stored in the CommandArgument
      // property to an Integer.
      int index = Convert.ToInt32(e.CommandArgument);
    
      // Retrieve the row that contains the button clicked
      // by the user from the Rows collection. Use the
      // CommandSource property to access the GridView control.
      GridView customersGridView = (GridView)e.CommandSource;
      GridViewRow row = customersGridView.Rows[index];
    

    如果需要将命令参数保留为产品ID,则可以使用下面的代码访问行:

    GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
    

    然后可以使用的findcontrol()方法 GridViewRow 选择所需的控件。

    Label priceLabel = row.FindControl("priceLabel") as Label;
    

    在OP的评论后编辑

    如果我是正确的,您想访问您所在行的数据项吗?

    我认为这在rowcommand事件处理程序中是不可能的-我在其他论坛上做了一些挖掘,显然这个属性在 DataBind - MSDN this 说:

    只有在GridView控件的RowDataBound事件期间和之后,DataItem属性才可用。

    看起来您的方法或类似的东西是返回rowcommand中原始对象的唯一方法(希望有人证明我是错误的)。

    推荐文章