Reputation: 773
I have a gridview with 1 hidden column and 6 columns. I am trying to get the value of the hidden column row when the user clicks the button within the row but it does not pick up the hidden column. It gets the value of the first column which is the first visible column(FirstName).
Is there a way to get the value of the hidden column(UserID) ?
This is what I have:
C#
<asp:GridView ID="gvUsers" runat="server" AutoGenerateColumns="false" class="table table-bordered" ClientIDMode="Static" DataKeyNames="UserID, Firstname" OnRowCommand="gvUsers_RowCommand" OnRowDeleting="gvUsers_RowDeleting">
<Columns>
<asp:BoundField DataField="UserID" Visible="false" HeaderText="UserID" />
<asp:BoundField DataField="FirstName" HeaderText="First Name" />
<asp:BoundField DataField="LastName" HeaderText="Last Name" />
<asp:BoundField DataField="Username" HeaderText="Username" />
<asp:BoundField DataField="Phone" HeaderText="Cellphone Number" SortExpression="EventDescription" />
<asp:BoundField DataField="Email" HeaderText="Email" SortExpression="EventDescription" />
<asp:TemplateField HeaderText="Action">
<ItemTemplate>
<asp:Button ID="btnTest" runat="server" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
jQuery:
<script type="text/javascript">
$(function () {
$('[id*=btnTest]').on("click", function () {
var id = $(this).closest("tr").find('td:eq(0)').text();
alert(id);
return false;
});
});
</script>
Please assist how I can get the hidden column value when the button is clicked. Thank you.
Upvotes: 2
Views: 1297
Reputation: 35514
The easiest way is to just add it to a TemplateField in an element that is hidden
<asp:TemplateField>
<ItemTemplate>
<span style="display:none"><%# Eval("UserID") %></span>
<asp:Button ID="btnTest" runat="server" Text="Button" />
</ItemTemplate>
</asp:TemplateField>
And modify the script to
var id = $(this).closest("tr").find('span').html();
Update
As @Taplar mentioned, you can also use attributes. But you need to add those in the RowDataBound event.
if (e.Row.RowType == DataControlRowType.DataRow)
{
DataRowView row = e.Row.DataItem as DataRowView;
e.Row.Attributes.Add("data-userid", row["userid"].ToString());
}
The script would then become
var id = $(this).closest("tr").data('userid');
Upvotes: 2