Friday, 25 May 2012

Get ASP.Net GridView SelectedRow when clicked using JavaScript


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <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;
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns = "false" AllowPaging = "true"OnPageIndexChanging = "PageIndexChanging">
        <Columns>
        <asp:BoundField DataField = "CustomerID" HeaderText = "CustomerID" />
        <asp:TemplateField HeaderText = "City">
            <ItemTemplate>
                <asp:TextBox ID="txtCity" runat="server" Text = '<%# Eval("City") %>'></asp:TextBox>
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <ItemTemplate>
                <asp:LinkButton ID="lnkSelect" runat="server" Text="Select" CommandName = "Select" OnClientClick ="return GetSelectedRow(this)" />
            </ItemTemplate>
        </asp:TemplateField>
        </Columns>
    </asp:GridView>
    </form>
</body>
</html>
 
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.
 
Demo
 
Downloads

No comments:

Post a Comment

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