All posts tagged 'aspnet-gridview-javascript'

How to Work With a GridView Row in JavaScript

by JBrooks 14. July 2009 16:40

The question came up asking how to change something in a GridView row based on something else in that row without doing a postback.   So I created a simple example where if you check a CheckBox then another column in that row would have it's background color changed.  I did this in a generic way by sending the checkbox to the function by using the keywork "this" and then getting a reference to the row.  Here is what it looks like:

So when you check the CheckBox for a given row, it's "Name" column's background changes color to Aqua.

Here is the code behind to bind the table:

using System;
using System.Data;

namespace BlogTests
    public partial class _Default : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
        if (!IsPostBack)
               DataTable dt = new DataTable();

                dt.Columns.Add("Include", typeof(Boolean));
                dt.Columns.Add("Name", typeof(String));
                dt.Rows.Add(new Object[] { 0, "Jim" });
                dt.Rows.Add(new Object[] { 0, "Jen" });
                dt.Rows.Add(new Object[] { 0, "Kylie" });
                GridView1.DataSource = dt;



and then the .aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="BlogTests._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="">
<head runat="server">
    <title>Row Test</title>
    <style type="text/css">
            background-color: Aqua;
            font-weight: bold;

    <script type="text/javascript">
        function toggleSelected(sender) {
            var row = GetParentElementByTagName(sender, "TR");

            if (sender.checked)
                row.cells[1].className = "selected";
                row.cells[1].className = '';


        function GetParentElementByTagName(element, tagName) {
            var element = element;
            while (element.tagName != tagName)
                element = element.parentNode;
            return element;

    <form id="form1" runat="server">
    <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False">
            <asp:TemplateField HeaderText="Include" SortExpression="Include">
                    <asp:CheckBox ID="CheckBox1" runat="server" Checked='<%# Bind("Include") %>' onclick="toggleSelected(this)" />
            <asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name">
                <ItemStyle HorizontalAlign="Left" />



ASP.Net | Development | GridView