【问题标题】:Get gridview values from code behind从后面的代码中获取 gridview 值
【发布时间】:2012-01-15 00:01:18
【问题描述】:

我想从代码隐藏中获取网格视图中隐藏字段的值,但不用于_RowDataBound 或任何其他类似方法。这是我现在的代码(这是一个购物车场景):

<asp:GridView ID="gvShoppingCart"
runat="server"
AutoGenerateColumns="False"
AllowPaging="True"
DataKeyNames="ID"
ShowFooter="true">
<Columns>
    <asp:TemplateField>
        <ItemTemplate>
            <asp:HiddenField ID="lblProductID" runat="server" Text='<%# Eval("ProductID") %>' />
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Product">
        <ItemTemplate>
            <asp:HyperLink ID="HyperLink1" runat="server" 
                NavigateUrl='<%# Eval("ProductID", "product_details.aspx?id={0}") %>' 
                Text='<%# GetProduct(Eval("ProductID")) %>'></asp:HyperLink>
        </ItemTemplate>
    </asp:TemplateField>
    <asp:TemplateField HeaderText="Quantity">
        <ItemTemplate>
            <asp:TextBox ID="txtQuantity" runat="server" Width="35" CssClass="input" onkeypress="return isNumberKey(event)" AutoPostBack="true" ontextchanged="txtQuantity_TextChanged"></asp:TextBox>
        </ItemTemplate>
    </asp:TemplateField>
</Columns>

为了简洁起见,我删除了某些字段,因为它们仅用于显示。数量字段可供用户输入一个数字以将许多产品添加到他的购物车中。我希望在_TextChanged 事件中访问lblProductID 标签。在同一事件中,我尝试了

Label lblProductID = (Label)gvShoppingCart.FindControl("lblProductID");

但它不起作用并且只返回一个空值。解决办法是什么?

【问题讨论】:

  • 如果你没有使用gridView事件,当你有几十个这样的控件时,你怎么知道返回哪个lblProductID。我建议你使用事件冒泡。使用 RowCommand 代替 _TextChanged

标签: c# asp.net gridview code-behind


【解决方案1】:

对于GridView 中的每一行,ProductID 都有一个HiddenField

您可以使用以下代码访问一行的HiddenField(在第一行下方的示例中)(假设您的HiddenField 在第一个单元格中):

HiddenField hiddenFieldProductID = 
           (HiddenField)gvShoppingCart.Rows[0].Cells[0].FindControl("lblProductID");

string productID = hiddenFieldProductID.Value

// Do something with the value

希望,这会有所帮助。

【讨论】:

  • 那他如何识别rowIndex呢?记住他不想使用网格事件
  • @nuux:在 TextChanged 事件中,发送者引用了 TextBox 控件。从那里您可以通过访问 ((Control)sender).Parent.Parent. 到达 Control 行
  • @nuux:我刚刚看到你对这个问题的评论。当然,RowCommands 也是一种选择。
【解决方案2】:

尝试将 HiddenField 替换为标签或文本框,并将 visible 属性设置为 false。 我以前试过这个,它有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-15
    • 1970-01-01
    • 2016-05-21
    • 2011-07-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多