Search This Blog

Monday, March 14, 2011

Highlight gridview row when row is selected using javascript


Many of us like to highlight or supposed to highlight the selected row in the grid view control, if we are doing it in the server side it will take time when there is no of rows, if we go for java script then it will be easy and we can do it with a few lines of server side coding.

In this example I have used the alternate row color from my grid view color, so If you need the same way you have to change the alternate row color in this java script.

Javascript:

<script type="text/javascript">
var gridViewCtlId = '<%=gvSample.ClientID%>';
var gridViewCtl = null;
var curSelRow = null;
var oddrowcolor = null;
var evenrowcolor = null;
function getGridViewControl() {
if (null == gridViewCtl) {
gridViewCtl = document.getElementById(gridViewCtlId);
}
}
function onGridViewRowClick(rowIndex) {
var table = document.getElementById("gvSample");
for (var i = 1; i < table.rows.length-1; i++) {
if (i % 2 != 1) {
table.rows[i].style.backgroundColor = '#FFFFFF';
}
else {
table.rows[i].style.backgroundColor = '#fffbd6';
}
}
var selRow = getClickedRow(rowIndex);
if (null != selRow) {
selRow.style.backgroundColor = '#FFCC33';
}
}

function getClickedRow(rowIndex) {
getGridViewControl();
if (null != gridViewCtl) {
return gridViewCtl.rows[rowIndex];
}
return null;
}
</script>

C# Code Behind:

protected void gvSample_RowCreated(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
int rowid = Convert.ToInt32(e.Row.RowIndex) + 1;
e.Row.Attributes.Add("onclick", "onGridViewRowClick('" + rowid.ToString() + "')");
}
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.