hmk hmk - 1 year ago 68
Javascript Question

How to change the gridview row colors in onclick event in javascript?

I wrote the following

GridView
code in ASP.NET. I set the
AlternatingRow
style's
BackColor
to bisque. The remaining rows are set to white.

This code exists within my
grdRequests_RowDataBound
event:

if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Attributes.Add("onclick", "ChangeRowColor(this)");
e.Row.Attributes.Add("onmouseover", "this.style.cursor=\'pointer\'");
}


The JavaScript
ChangeRowColor
code above is as follows:

function ChangeRowColor(row)
{
if (previousRow == row)
return;

else if (previousRow != null)
var color = row.style.backgroundColor;

if (previousRow != null) {

alert(color)

if (color == "bisque") {
previousRow.style.backgroundColor = "white";
}
else if (color == "white") {
previousRow.style.backgroundColor = "bisque";
}
}

row.style.backgroundColor = "#ffffda";
previousRow = row;
}


When I click the row, I need to change the color like yellow. After selecting another row, I need to switch the previous row's color back to its old color, but in my code this doesn't work. Any suggestions?

Answer Source

you can do like this...

 protected void MyGridView_RowCreated(object sender, GridViewRowEventArgs e)
 {

    string rowStyle = "this.style.backgroundColor
    = 'yellow'";
    string rowStyleClickedTwice =
    "this.style.backgroundColor = 'blue'";
    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 + "'" + ")");
    }       
}

And this is the Java Script code:

 <input type="hidden" id="hiddenColor"  />
 <script language ="javascript" type="text/javascript">

  document.body.style.cursor = 'pointer'; 


 function ChangeRowColor(rowID) 
 { 
     var color = document.getElementById(rowID).style.backgroundColor;
     alert(color);   

     if(color != 'yellow') 
     document.getElementById("hiddenColor").style.backgroundColor = color;

     alert(oldColor); 

     if(color == 'yellow')
    document.getElementById(rowID).style.backgroundColor = document.getElementById("hiddenColor").style.backgroundColor;
     else
     document.getElementById(rowID).style.backgroundColor = 'yellow';             

  }
</script>

i hope it will helps you....