Wednesday, January 12, 2011

How to select and highlight a row in gridview using Javascript

If you have ever used the ASP.NET GridView control , you will know that the user is able to select rows within the grid. While this is a great feature of the GridView control, you would normally have to select a row using a CommandField or a hyperlink column with a CommandName="Select" property included. This, I think just looks a bit naff.

Surely, there is a better way. Well luckily there is, we can simply use client side JavaScript to do the row selection. That is what this article is all about. The code is minimal, and very easy to understand, but I think it is useful code, and I also think it is something that anyone that works with the GridView control should know.

How It Works





function onGridViewRowSelected(rowIdx) {
var selRow = getSelectedRow(rowIdx);
if (curSelRow != null) {
curSelRow.style.backgroundColor = '#ffffff';
}

if (null != selRow) {
curSelRow = selRow;
curSelRow.style.backgroundColor = '#BA9999';
}
}

function getSelectedRow(rowIdx) {
getGridViewControl();
if (null != gridViewCtl) {
return gridViewCtl.rows[rowIdx];
}
return null;
}


Explanation: This method gets row id of the clicked row as argument. we first get the gridview control using GetGridViewControl() function then in getSelectedRow() function we reach to that particular row. Finally we color that row to make it look selected.

That's it

And that as they say is that. Simple wasn't it. But I think it's a useful one, I have always wondered how my online bank did produced such a nice grid.

Conclusion

Well that's it actually. Although the code is very simple, I'm sure you'll agree this JavaScript selection method sure looks better than having a button column, or a hyperlink column to do the row selection. And it's more intuitive, I think. The users simply point and click the row they want, job done.


No comments:

Post a Comment