Saturday, July 19, 2008

How to Extract values from GridView Selected Row using DataKeys

To extract values from a Gridview selected row generally we use the following method.

Gridview1.Rows[Gridview1.SelectedIndex].cells[1].Text

The above method only works when the Gridview BoundField is in visible state. If we set the boundfield as visible="false", then the above code will fail to serve the purpose. To Extract values from invisible column of an Gridview we can use DataKeys propery. The following example shows how to use the DataKeys property to determine the data key value of the GridView selected row.

<asp:gridview id="JobsGridVeiw"
     datasourceid="JobsDataSource"
     autogeneratecolumns="false"
     datakeynames="JobID"
     onselectedindexchanged="JobsGridVeiw_SelectedIndexChanged"
    runat="server">
<Columns>
     <asp:boundfield datafield="JobID"
         readonly="true" visible="false"/>
     <asp:boundfield datafield="JobType"
        convertemptystringtonull="true" headertext="Job Type"/>
     <asp:boundfield datafield="JobNo"
        convertemptystringtonull="true" headertext="Job No"/>
     <asp:boundfield datafield="JobStatus"
        convertemptystringtonull="true" headertext="Job Status"/>
     <asp:boundfield datafield="JobDesc"
        convertemptystringtonull="true" headertext="Description"/>
</Columns>
</asp:gridview>

In the above example the BoundField JobID is set as visible="false". If you want to extract the value of JobID column you need to use the following code.

void JobsGridVeiw_SelectedIndexChanged(Object sender, EventArgs e)
{
    string JobID = JobsGridVeiw.DataKeys[JobsGridVeiw.SelectedIndex].Value.ToString();
}

Hope this post help u.