Navigation

Search

Categories

On this page

Gridview Hidden Field, How to get hidden field value in gridview

Archive

Blogroll

Disclaimer
The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

RSS 2.0 | Atom 1.0 | CDF

Send mail to the author(s) E-mail

Total Posts: 112
This Year: 50
This Month: 0
This Week: 0
Comments: 0

Sign In

 Monday, March 03, 2008
Monday, March 03, 2008 12:44:01 PM (Eastern Standard Time, UTC-05:00) ( )

 

A GridView contains a property called "DataKeyNames" which is typically the primary key of each record.  This is often useful when you need to grab the unique recordID for each row.  To get ID for a single selected row, you can do something like this:

If you are using RowUpdating, RowDatabound, etc.

Dim intId as Integer= GridView1.DataKeys(e.RowIndex).Value

By name :

Dim intId as Integer= GridView1.DataKeys("ID").Value 

By Index:

Dim intId as Integer= GridView1.DataKeys(0).Value
<Columns>

<asp:TemplateField>
<ItemTemplate>
<asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("ID") %>' />
</ItemTemplate>
</asp:TemplateField>

To get the ID value for a group of records in a Gridview, you can do something like this:

Protected Sub btn_ExportSelectedRecords_Click(ByVal sender As Object, ByVal e As System.Web.UI.ImageClickEventArgs)
        'First loop through the GridView and see which IDs were selected. I use the StringBuilder since the list could be a very long list        
        Dim sb As New StringBuilder
        Dim row As GridViewRow
        For Each row In searchResultsGridView.Rows
            If (CType(row.FindControl("CheckBox1"), CheckBox)).Checked Then
                lblSelectedIDDirs.Text = sb.Append(searchResultsGridView.DataKeys(row.RowIndex).Value.ToString() + ","c).ToString()
            End If
        Next
End Sub
<asp:GridView ID="searchResultsGridView" Runat="server" DataSourceID="searchResultsDataSource" AllowSorting="true" AllowPaging="true" PageSize="20" 
 DataKeyNames="IDDir">
                       
 <Columns>
              
 <asp:TemplateField HeaderText="">
 <ItemTemplate>
                    <asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("IDDir") %>' />
                </ItemTemplate>
                </asp:TemplateField> 
                
                 <asp:TemplateField HeaderText="">
                 <ItemTemplate>
                    <asp:Checkbox id="Checkbox1" runat="server" /> 
                 </ItemTemplate>
                </asp:TemplateField>