views:

38

answers:

3

Hi I have a gridview:

<asp:GridView ID="gridData" runat="server" AutoGenerateColumns="false" CellPadding="3" AllowSorting="true" CssClass="CartContentTable" GridLines="horizontal" Width="100%" OnDataBound="addLabelsWhereNeeded">
     <ItemTemplate>
         <asp:HiddenField ID="hdField" runat="server" Value='<%# Eval("CartItemGuid")%>' />
     </ItemTemplate>
</asp:GridView>

I want to access the value in the hidden field in my code behind. I know i need to do this when the item is bound but i cant seem to work out how to do it.

protected void addLabelsWhereNeeded(object sender, EventArgs e)
{

   // Get Value from hiddenfield
}
A: 

yes you are right. You must do it on ItemDateBound. Check It must work

AEMLoviji
How! thats why im asking. Ive done it with a repeater before but i cant seem to use the same properties in a gridview. I know its something along these lines but cant seem to get the value. ((HiddenField)e.....(hdField)).Value;
phil crowe
A: 

Try adding

OnRowDataBound="addLabelsWhereNeeded"

to your GridView. Then cast the control in the corresponding cell to a HiddenField to grab the value:

protected void addLabelsWhereNeeded(object sender, GridViewRowEventArgs e)
{
    HiddenField hf = e.Row.Cells[0].Controls[1] as HiddenField;
    String theValue = hf.Value;
}

assuming you've defined your GridView as:

<asp:GridView runat="server" ID="gv" OnRowDataBound="addLabelsWhereNeeded"> 
    <Columns>
        <asp:TemplateField> 
          <ItemTemplate>
                <%--your hidden field--%>
          </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView> 

Just make sure you are indexing the correct cell and correct control within that cell.

Brissles
sorry im really dumb. I havent used gridviews before. Im actually trying to amend someone elses code. Can you explain what the 'cell' number is?
phil crowe
The number is used as a cell index for that row. Say you have ColumnA, ColumnB and ColumnC defined in your gridview. In your code-behind, indexing with Cell[0] would be ColumnA in that row, and indexing with Cell[2] would be ColumnC in that row.
Brissles
A: 

I do quite see what you want to achieve with this private field while databinding? In the RowDataBound Event you can access the whole data item, so there is no need for the use of a hidden value.

Pseudocode:

protected void Grid1_RowDataBound(object sender, GridViewRowEventArgs)
{
 if(e.RowType == RowType.DataRow)
 {

 }
}

Set a Breakpoint into if clause and use quickwatch to see how you need to cast the DataItem that is currently bound to gain full access to all properties, even if they aren't bound to any control.

citronas