Friday, 25 May 2012

Get ASP.Net GridView SelectedRow when clicked using JavaScript

<html xmlns="">
<head runat="server">
    <script type = "text/javascript">
        function GetSelectedRow(lnk) {
            var row = lnk.parentNode.parentNode;
            var rowIndex = row.rowIndex - 1;
            var customerId = row.cells[0].innerHTML;
            var city = row.cells[1].getElementsByTagName("input")[0].value;
            alert("RowIndex: " + rowIndex + " CustomerId: " + customerId + " City:" + city);
            return false;
    <form id="form1" runat="server">
    <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns = "false" AllowPaging = "true"OnPageIndexChanging = "PageIndexChanging">
        <asp:BoundField DataField = "CustomerID" HeaderText = "CustomerID" />
        <asp:TemplateField HeaderText = "City">
                <asp:TextBox ID="txtCity" runat="server" Text = '<%# Eval("City") %>'></asp:TextBox>
                <asp:LinkButton ID="lnkSelect" runat="server" Text="Select" CommandName = "Select" OnClientClick ="return GetSelectedRow(this)" />
Above you will notice that I have a simple ASP.Net GridView. The last column has an ASP.Net LinkButton lnkSelect to select the GridView Row and find its RowIndex as well as the Bound Fields and Template Fields.
When the Select LinkButton is clicked, I first identify the GridView Row and then using it I find the column values as well as access the controls inside the Template Fields.

No comments:

Post a Comment

Note: only a member of this blog may post a comment.