Often times you want to display data for users to see and allow them to select it. But you really want to return a key value and not the data you have displayed for them. So the question is how do you get the hidden key value. The defined way is the use the 'datakeynames' parameter on the gridview and get the hidden values using the code-behind.
However, what do you do if you wish to access the key value from javascript? Well, then you have to set up your gridview to store the data but not display it. I have found a couple of ways to do this:
1) add a template field with a label in it and set the 'style' to display:none.
[code]
<asp:TemplateField >
<ItemTemplate>
<asp:Label id="lblUK" runat="server" text='<%# Eval("uniquekey")%>' Style="display:none" ></asp:Label>
</ItemTemplate>
</asp:TemplateField>
[/code]
2) Add a bound field, and set the class or itemstyle-cssClass to a value and set that value in your style sheet with the display:none parm.
[code]
<asp:BoundField DataField="uniquekey" HeaderText=""
ItemStyle-CssClass="hideGridColumn" >
</asp:BoundField>
<style type="text/css">
.hideGridColumn
{
display: none;
}
</style>
to access from javascript:
function getSelectedRow(row)
{
var ctlGridView = row.parentNode.parentNode;
var Code = row.cells[0].innerHTML;
var Type = row.cells[1].innerHTML;
var uk = row.cells[4].innerText;
row.style.backgroundColor = "red";
alert("Code:" + Code + " Type:" + Type + " uk:" + uk);
return true;
}
in the code behind add onclick value to call this function:
Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
'set the mouseover values
For Each row As GridViewRow In GridView1.Rows
If row.RowType = DataControlRowType.DataRow Then
row.Attributes("onmouseover") = "this.style.fontWeight='bold';"
row.Attributes("onmouseout") = "this.style.fontWeight='normal';"
row.Attributes("onclick") = "getSelectedRow(this);"
End If
Next
MyBase.Render(writer)
End Sub
[/code]
Now both of the methods have the actual data in the HTML source, so if it is sensitive data, you would not want to do this. But if the data is not sensitive, it is a good way to allow access to hidden values from javascript.