Introduction:
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.
The Row Created Event of the GridView:
Like my last article "Changing
GridView Row Color OnMouseOver" I used the same approach in populating the
GridView. The difference lies in the RowCreated event of the GridView control.
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 +
"'" +
")");
}
} |
As, you can see in the method above I am
assigning different ids to the rows by embedding the id attribute. This will
help me distinguish one row from the other. Later, on the onclick attribute I
attach the Java Script function "ChangeRowColor" which is responsible for
changing the color of the GridView row. The ChangeRowColor function takes in the
id of the row. Let's take a look at the ChangeRowColor function.
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.
I have attached the project files at the end of
this article please feel free to download it.
I hope you liked the article, happy coding!