Click here to Skip to main content
Email Password   helpLost your password?

Introduction

This article is about changing the color of a GridView row on mouse click without having a postback on the page. In order to achieve this we will be using some javascript and off course the GridView Control itself :).

Background

GridView is a server side control that contains Rows and Columns. In some cases we want to do something more than the straight forward functionality of the GridView control depending on the functional/UI requirements of the application.

Using the code

Following javascript will be used to change the color of the row.

        <script type="text/javascript">
        //variable that will store the id of the last clicked row
        var previousRow;
        
        function ChangeRowColor(row)
        {
            //If last clicked row and the current clicked row are same
            if (previousRow == row)
                return;//do nothing
            //If there is row clicked earlier
            else if (previousRow != null)
                //change the color of the previous row back to white
                document.getElementById(previousRow).style.backgroundColor = "#ffffff";
            
            //change the color of the current row to light yellow

            document.getElementById(row).style.backgroundColor = "#ffffda";            
            //assign the current row id to the previous row id 
            //for next row to be clicked
            previousRow = row;
        }
     </script>

Following code will be required on GridView1_RowDataBound event

    Protected Sub GridView1_RowDataBound(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewRowEventArgs) _
        Handles GridView1.RowDataBound
        If (e.Row.RowType = DataControlRowType.DataRow) Then
            e.Row.Attributes.Add("onclick", "javascript:ChangeRowColor('" & e.Row.ClientID & "')")
        End If
    End Sub

    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
        If Not IsPostBack Then
            'FillDataTable is a function that will return a DataTable
            'with some values and is available in the code for download.
            Me.GridView1.DataSource = Me.FillDataTable()
            Me.GridView1.DataBind()
        End If
    End Sub
        

Before clicking the row

After clicking the row

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
Generalupdate PreviousRowColor
Member 4401654
21:53 15 Apr '09  
Hey faraz it helped me alot. Thanks
But in previousColor case you can make this more generalize, right now you are changing PreviousRowColor into white, which wont be same in all cases. You may update your code something like this.


<script type="text/javascript">
//variable that will store the id of the last clicked row
var previousRow;
var previousColor;
function ChangeRowColor(row)
{
//If last clicked row and the current clicked row are same
if (previousRow == row)
return;//do nothing
//If there is row clicked earlier
else if (previousRow != null)
//change the color of the previous row back to white
document.getElementById(previousRow).style.backgroundColor = previousColor;
//change the color of the current row to light yellow
previousColor=document.getElementById(row).style.backgroundColor;
document.getElementById(row).style.backgroundColor = "orange";
//assign the current row id to the previous row id
//for next row to be clicked
previousRow = row;
}
</script>




Thanks
NOuman Rasheed

may i get your id over there?

GeneralHi faraz
VimalSaifudin
20:40 26 Sep '08  
Very Nice.....I too works in the UAE in the same field
GeneralGreat Solution But How Do I Handle Postbacks?
eggnturtle
12:45 20 Sep '08  
Hi,
Your solution works perfectly except I am having issues with postback. Initially, I click a row in grid - it changes row color fine. However, if I select a different item from a drop-down list on my page, everything is refreshed (including grid) and then it wont highlight row anymore.

I tried a different solution than yours first, and found through alerts in my javascript that it found the grid (was not null) but its rows.length had changed to 0 even though there were rows in the grid. Please explain how this should be handled. Thank you so much!
GeneralRe: Great Solution But How Do I Handle Postbacks?
farazsk11
21:06 20 Sep '08  
Well what is in the code is completely client side and will not handle things for postback. How ever if you can keep track of what rows are clicked and color is changed you might be able to change the color again on postback for which you have to write additional code.

Faraz Shah Khan
MCP, MCAD.Net, MCSD.Net, MCTS-Win/Web, MCPD-Web
Blog

GeneralRe: Great Solution But How Do I Handle Postbacks?
eggnturtle
5:14 21 Sep '08  
Hmmm, I added a bunch of alerts to the javascript and it works MOST of the time. Every so often if I select another item in dropdown and grid rebinds, it will highlight on the first click and then nothing. Very strange. Your functions passing of clientID is definitely better than the other way... I'll just keep monitoring it for now. Thanks again.
GeneralGood work
Member 4183408
20:05 8 Sep '08  
It is a good work I appreciate it .Keep it up
GeneralRediculously simplistic
Oakman
13:40 5 Apr '08  
This isn't an article, it's a piece of fluff

Jon
Smith & Wesson: The original point and click interface

GeneralRe: Rediculously simplistic
farazsk11
19:48 5 Apr '08  
Thanks for the comments indeed its quite simple, probably for you and me but what about those people who ask how to display MessageBox through javascript. It is mainly for beginners.

Faraz Shah Khan
MCP, MCAD.Net
Blog

GeneralRe: Rediculously simplistic
Oakman
2:24 6 Apr '08  
farazsk11 wrote:
It is mainly for beginners.

Your code is a copy of http://www.gridviewguy.com/ArticleDetails.aspx?articleID=174_Change_GridView_RowColor_OnMouseClick You didn't even change the function name.

Jon
Smith & Wesson: The original point and click interface

GeneralRe: Rediculously simplistic
farazsk11
3:17 6 Apr '08  
I checked that artcile written by Azam, well bro first why do I need to copy the code, second searching on internet can bring almost everything in front of you, so if I have copied any thing I must have changed it. Most importantly such childish act neither suits my qualification nor my experience. Well I must say its a coincidence. Any way no objections, if you fell like that you can Report This Article.

Faraz Shah Khan
MCP, MCAD.Net
Blog

GeneralMultiple Rows
DigitalRacer
12:56 4 Apr '08  
*throws down gauntlet*

I think multiple row selection would add some value, otherwise the code is pretty simple, but still nice. I voted a 4.

DR
GeneralRe: Multiple Rows
farazsk11
19:44 5 Apr '08  
Hi,

If you remove this check.

else if (previousRow != null)
document.getElementById(previousRow).style.backgroundColor = "#ffffff";

it will work for multiple rows as well. a slight change may require to deselect the rows in the first if check.

Faraz Shah Khan
MCP, MCAD.Net
Blog

GeneralGood Work
Irwan Hassan
18:41 26 Mar '08  
Hi, you have done a good work and simple and easy javascript to implement. Have a nice day.
GeneralRe: Good Work
farazsk11
16:43 27 Mar '08  
thanks.

Faraz Shah Khan
MCP, MCAD.Net
Blog

Generalthanks
jomet
18:53 19 Mar '08  
cool feature!!!
but i cant download your source code. Cry
thanks Laugh
GeneralRe: thanks
farazsk11
7:37 20 Mar '08  
Hi, well I will try to reupload the code I am not sure why its not taking the file because at the time of writting this article I uploaded all the files and the zip file was there. Any way I will check again.

Faraz Shah Khan
MCP, MCAD.Net
Blog


Last Updated 19 Mar 2008 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010