How To Change The color of GridView Row Color by Using Simple Mouse Click

In this article I will demonstrate that how you can change the color of the GridView row by using simple mouse click and change it back to its original color by clicking the row twice. Take a look at the RowCreated event below to have a better idea: protected void MyGridView_RowCreated(object sender, GridViewRowEventArgs e) { string rowID = String.Empty; if (e.Row.RowType == DataControlRowType.DataRow) { rowID = "row"+e.Row.RowIndex; e.Row.Attributes.Add("id","row"+e.Row.RowIndex); e.Row.Attributes.Add("onclick","ChangeRowColor(" +"'" + rowID + "'" + ")"); } } JavaScript Function: <script language ="javascript" type="text/javascript"> document.body.style.cursor = 'pointer'; var oldColor = ''; function ChangeRowColor(rowID) { var color = document.getElementById(rowID).style.backgroundColor; if(color != 'yellow') oldColor = color; if(color == 'yellow') document.getElementById(rowID).style.backgroundColor = oldColor; else document.getElementById(rowID).style.backgroundColor = 'yellow'; } </script> The ChangeRowColor function takes in the id of the row and finds the color of the row. Then it checks that if the color is 'yellow' which, is the color of the highlight row. If it is not yellow then it simply assigns the color to the public variable oldColor which is used to save the previous color of the GridView row. If the color is yellow then we get the previous color and assign to the row so that it can come back to its original state.

No comments:

Post a Comment