chris05
chris05

Reputation: 735

Get gridview values from code behind

I want to get the value of a hidden field in a grid view from code-behind, but not to be used in the _RowDataBound or any other similar method. Here is my present code (it is a shopping cart scenario):

<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>

For the sake of brevity I removed certain fields since they are there only for the display. The Quantity field is there for the user to input a number to add a number of products to his cart. I wish to access the lblProductID label in the _TextChanged event. In this same event, I tried

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

but it didn't work and returns only a null value. What is the solution?

Upvotes: 1

Views: 7664

Answers (2)

Hans
Hans

Reputation: 13040

For each row in your GridView there is a HiddenField for the ProductID.

You can access the HiddenField of a row (in the example below the first row) by using the following code (assuming your HiddenField is in the first cell):

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

string productID = hiddenFieldProductID.Value

// Do something with the value

Hope, this helps.

Upvotes: 1

Anwar
Anwar

Reputation: 4508

Try to replace the HiddenField to a label or a textbox and set the visible attribute to false. I had tried this before and it works.

Upvotes: 0

Related Questions