Jan
19
Written by:
Steve Gray
1/19/2010 11:12 AM
You can’t make a field ‘not visible’ in a GridView control, it just won’t render. That’s not helpful at all. The way to retrieve a hidden field (usually a key field) is to assign it to the ‘DataKeyName’ property of the GridView. The GridView will automatically populate that collection, and it can be retrieved in the code behind.
Assigning the DataKeyName:
<asp:GridView ID="GridView1" AutoGenerateColumns="false"
runat="server" DataKeyNames="dashboardID"
HeaderStyle-CssClass="gridviewHeader" >
<Columns>
<asp:BoundField DataField="dashboardDesc" HeaderText="Dashboard" />
<asp:TemplateField HeaderText="Select">
<ItemTemplate>
<asp:CheckBox ID="chkSelect" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
Retrieving the Key. This method iterates through the grid line by line. We’re also retrieving the value of a control in a Template Field:
For a = 0 To Me.GridView1.Rows.Count - 1
'get the value of a control in a template column
Dim chkSelect As CheckBox = _
CType(Me.GridView1.Rows(a).FindControl("chkSelect"), CheckBox)
'get the data key
Dim row As GridViewRow = GridView1.Rows(a)
Dim strDashboardID As String = GridView1.DataKeys(a).Value
Next
Here’s the same idea, but from within the RowCommand
Protected Sub GridView4_RowCommand(ByVal sender As Object, _
ByVal e As System.Web.UI.WebControls.GridViewCommandEventArgs) _
Handles GridView4.RowCommand
' Convert the row index stored in the
'CommandArgument property to an Integer.
Dim index As Integer = Convert.ToInt32(e.CommandArgument)
' Get the
Dim selectedRow As GridViewRow = GridView4.Rows(index)
Dim lnkPAContName As LinkButton = _
CType(selectedRow.Cells(0).Controls(0), LinkButton)
Dim strContName As String = lnkPAContName.Text
Me.txtProjectDesc.Text = strContName
Dim strPAContID As String = GridView4.DataKeys(index).Value
Session("PAContID") = strPAContID
End Sub
Here’s a third approach. If you’re using a template control, the CommandArgument will not be correctly populated with the index. Here’s an alternative way to get the current row index:
Dim lnkFileName As LinkButton = CType(e.CommandSource, LinkButton)
Dim selectedRow As GridViewRow = lnkFileName.BindingContainer
Dim strOutputType As String =_
GridView1.DataKeys(selectedRow.DataItemIndex).Value