Highlight GridView Rows Using Checkboxes
By AzamSharp
Views: 12550

Introduction:

 

Most of us are familiar with how to select the GridView rows using checkboxes. This article goes one step further and highlights the checked rows in the GridView control.

 

Populating the GridView Control:

 

The first step is to populate the GridView control. I am using the Northwind database “Categories” table in this demo. Check out the code below:

 

private void BindData()

    {

        gvCategories.DataSource = GetData();

        gvCategories.DataBind();

    }

   

    private DataSet GetData()

    {

        string connectionString = "Server=localhost;Database=Northwind;Trusted_Connection=true";

        SqlConnection myConnection = new SqlConnection(connectionString);

 

        SqlDataAdapter ad = new SqlDataAdapter("SELECT * FROM Categories", myConnection);

        DataSet ds = new DataSet();

        ad.Fill(ds);

 

        return ds;

    }

 

The GetData() method simply fills the DataSet with the data from the “Categories” table and return to the BindData() method. The BindData method populates and bind the GridView control.

 

HTML Code for the GridView Control:

 

I have used TemplateFields inside the GridView control. Let’s check out the HTML code for the GridView control.

 

<asp:GridView ID="gvCategories" runat="server" AutoGenerateColumns="False" BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px" CellPadding="2" ForeColor="Black" GridLines="None">

   

    <Columns>

   

    <asp:TemplateField>

    <ItemTemplate>

    <asp:CheckBox ID="chkSelect" runat="server" onclick="changeColor(this)" />

    </ItemTemplate>

    </asp:TemplateField>

   

    <asp:TemplateField HeaderText="Name">

    <ItemTemplate>

    <asp:Label ID="lblCategoryName" runat="server" Text='<%# Eval("CategoryName") %>' />

    </ItemTemplate>

    </asp:TemplateField>

   

    <asp:TemplateField HeaderText="Description">

    <ItemTemplate>

    <asp:Label ID="lblDescription" runat="server" Text='<%# Eval("Description") %>' />

    </ItemTemplate>

    </asp:TemplateField>

   

    </Columns>

        <FooterStyle BackColor="Tan" />

        <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue" HorizontalAlign="Center" />

        <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />

        <HeaderStyle BackColor="Tan" Font-Bold="True" />

        <AlternatingRowStyle BackColor="PaleGoldenrod" />

   

    </asp:GridView>   

 

The most important line in the HTML code is the declaration of the CheckBox control.   

 

<asp:CheckBox ID="chkSelect" runat="server" onclick="changeColor(this)" />

 

I have attached the onclick event of the Checkbox to fire the changeColor function. The changeColor function takes the current object as the argument which in this case is the Checkbox control.

 

The Client Side Code:

 

Let’s take a look at the client side code where all the magic happens. Here is the changeColor function which is responsible for changing the color of the GridView checked row.

 

function changeColor(obj)

{      

    var rowObject = getParentRow(obj);

   

    var parentTable = document.getElementById("gvCategories");  

   

    if(color == '')

    {

        color =  getRowColor();     

    }   

   

    if(obj.checked)

    {             

        rowObject.style.backgroundColor = 'Yellow';           

    }

    else

    {

   

        rowObject.style.backgroundColor = color;

        color = '';                

    }

   

    // private method

    function getRowColor()

    {

        if(rowObject.style.backgroundColor == '') return parentTable.style.backgroundColor;

        else return rowObject.style.backgroundColor;

    }

   

}

 

There are couple of interesting things to note in the changeColor method. First, I am using a getParentRow function to get the parent row of the Checkbox control. I can easily reference the parent using the following code:

 

Obj.parentElement.parentElement;

 

Although the above approach will work but it looks ugly. That is why I created a simple function getParentRow which will simply return the parent row of the object. Below is the implementation of the getParentRow function.

 

// This method returns the parent row of the object

function getParentRow(obj)

{

    do

    {

        if(isFireFox())

        {

            obj = obj.parentNode;

        }

        else {

        obj = obj.parentElement;

        }

    }

    while(obj.tagName != "TR")

  

   return obj;  

}

 

To make the code browser compatible I created another small method isFireFox() which, checks whether the user’s browser is FireFox or not.

 

function isFireFox()

{

    return navigator.appName == "Netscape";

}

 

The changeColor function also contains a private method getRowColor which simply returns the old color of the row.

 

This code will also work with GridView having different color alternate rows. The alternate rows are not assigned any color but they inherit the background color of the GridView control.

 

Check out the final result in the screen shot below:

 

 

I hope you liked the article, happy programming!

 

[Download Code]

 

By AzamSharp


Enter Comment/Feedback
  •  
  •  
  •  
  •  
  •  

Comments/Feedbacks
Subject: hi
Name: benhui
Date: 8/4/2007 11:45:49 AM
Comment:
good job,Azamsharp!
will you please tell me how to partly hight the characters in GridView, for example, make "Se" in "Seafood" highlight?
thanks.
Subject: hi
Name: Tapas
Date: 8/10/2007 2:15:49 AM
Comment:
hi Azam
it is really a good article , will you tell me how to show only footer template without the other fields i.e
itemtemplate


thanks
Tapas
Subject: I Read this article
Name: durgaprasad
Date: 8/10/2007 4:33:20 AM
Comment:
This is article is good
Subject: Problem.
Name: Aderson Rangel
Date: 8/20/2007 5:35:10 AM
Comment:
Whe I select two rows and then I check again the row this don't change the color, can you say me how I solution this problem?? please.
Subject: Does not work
Name: Kevin
Date: 8/20/2007 8:29:35 PM
Comment:
It does not work when select 2 rows and uncheck one.
Subject: problem in ur code
Name: ranjan
Date: 8/20/2007 10:30:21 PM
Comment:
hello sir

how r u.


i m ranjan. i was using ur code. but in this code one problem is that when i click on check box then gridview's color change but some time when i again click on same checkbox that was already checked not change the gridview color.

plz check it.


bytheway thanks for learn me. i am also trying


thank you


with regards


RANJAN
Subject: Connection Closing!?
Name: David
Date: 8/21/2007 4:49:05 AM
Comment:
I cant see where your connection is closed within the GetData method!!

This is a real waste of resources!
Subject: RE: Closing Connection
Name: AzamSharp
Date: 8/21/2007 6:37:44 AM
Comment:
Hi David,

The connection will be opened and closed by the SqlDataAdapter automatically.
Subject: comment
Name: bhumika
Date: 8/24/2007 3:30:55 AM
Comment:
hey goodwork
Subject: Very Help full code.
Name: Mansoor Ali
Date: 8/25/2007 4:20:21 AM
Comment:
This is very help full code for. However I was searching this kind of code.

Thanks,
AzamSharp
Subject: Good Job
Name: Mansoor Ali
Date: 8/25/2007 4:26:18 AM
Comment:
Dear Azam,

I realy Impressed with your knowledge. Dear I need some help about GridView.
I want CheckBox and TextBox in GridView. The Textbox will show Unit from Category. User will change the unit and then all checked rows will updated in database.

please give this favore, I will be very thankfull to you.
Subject: RE: Mansoor Ali
Name: AzamSharp
Date: 8/25/2007 9:03:21 PM
Comment:
Hi Mansoor Ali,

I am glad that you liked the article. You are referring to in-place editing behavior in the GridView control. Check out my articles on the GridView control and I am sure you will find many articles which provide this solution.
Subject: Hi
Name: M.Quyen
Date: 8/31/2007 1:29:38 AM
Comment:
Hi,
Thanks your code, AzamSharp.
To answer why someone uncheck the checkbox it doesn't change the color because you didn't format the GridView.
I think the doesn't have the 'onclick'. It's only on the

Thanks again.
Subject: repair posted feedback
Name: M.Quyen
Date: 8/31/2007 9:29:19 AM
Comment:
.........
I think asp:checkbox doesn't have the 'onclick'. It's only on the input type=checkbox

Thanks again,
Subject: repair posted feedback
Name: AzamSharp
Date: 9/1/2007 11:28:33 AM
Comment:
Hi M.Quyen,

ASP.NET Checkbox does not have the onclick event but you can use it. The reason is that ASP.NET checkbox is rendered as the input checkbox and the input checkbox has the onclick event.
Subject: Problems
Name: M.Quyen
Date: 9/4/2007 9:03:04 PM
Comment:
I think we have problem.
When I check 2 or more checkboxes and after that uncheck all of them, the GridView only change color the last check. And it repeats if you check 2 or more checkboxes.
So what's your idea, AzamSharp?

Thanks and best regards,
Subject: Good
Name: srinivas
Date: 9/5/2007 12:09:49 AM
Comment:
Very Good Explanation
Subject: RE: M.Quyen
Name: AzamSharp
Date: 9/5/2007 7:52:35 AM
Comment:
Hi M.Quyen,

How are you unchecking the checked rows? Are you doing it one by one or by using a "UnCheck All" checkbox. If you are using "Uncheck All" approach then you will need to iterate through the checkboxes and check if there color is changed if so then you set the previous color.
Subject: New to GridView
Name: Rao
Date: 10/8/2007 12:59:17 PM
Comment:
Dear All,

I am pretty to ASP.net.

I would like to show the ROOM NAME on the main screen based on ROOM ID which is in a different table.

Main screen with GridView is coonected to table where it has ROOM_ID.
When you select Edit, I am able to convert ROOM_ID to ROOM NAME and display in the drop down.But, when the user selects the ROOM NAME in the dropdown and selects UPDATE, then I will be thrown back with ROOM_ID on the main screen.

Basically, I would like to show ROOM NAME based on ROOM_ID on a different table.

Can sombody send me a sample code or any help would be greatly appreciated..

Thanks
Subject: about javascript
Name: ranjeet
Date: 10/29/2007 2:28:52 AM
Comment:
i have implemented the code on my project but javascript error on page is there can anyone guide how to handle the javacript error
Subject: RE: JavaScript Errors
Name: AzamSharp
Date: 10/29/2007 5:19:42 PM
Comment:
Hi ranjeet,

What JavaScript errors are you facing?
Subject: grid view expro
Name: vikas
Date: 11/16/2007 1:45:06 AM
Comment:
good
Subject: Using CSS Style Names
Name: samzon
Date: 3/7/2008 1:28:22 PM
Comment:
I did a search and found this code and while it worked it did not meet my needs as I use classnames instead of background color and what not.

Any way you can quickly modify this code to use css classnames instead.

I modified 3 lines of code in the change color function:

if(obj.checked){
rowObject.className = 'checked';
}
else{
rowObject.className = color;
color = '';
}

// private method
function getRowColor(){
return rowObject.className;
}

where 'checked' is a classname for my grid.
Subject: Error
Name: ninoo08
Date: 4/6/2008 5:26:04 AM
Comment:
Hi
I selected 3 (or more) rows, after I uncheck then error: any rows not return default background. Can you fix it?
thx your code.



Join WebHost4Life.com






Copyright GridViewGuy 2007-2008