How to make an ASP.NET Table row highlight and become clickable
You will also need to get round the limitation of the fact that the <a> tag is not allowed around a table row, so here are the two javascript functions that perform the magic:
function highlight(tableRow, active)
{
if (active)
{
tableRow.style.backgroundColor = '#cfc';
}
else
{
tableRow.style.backgroundColor = '#fff';
}
}
function link(Url)
{
document.location.href = Url;
}
And here's the method that adds the javascript to each row of the table as it is rendered:
string connstring = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=";
connstring += Server.MapPath("App_Data/NWind.mdb");
string query = "SELECT [CustomerID], [CompanyName], [ContactName], [Address], [City]";
query += " FROM [Customers]";
OleDbConnection conn = new OleDbConnection(connstring);
OleDbDataAdapter da = new OleDbDataAdapter(query, conn);
DataSet ds = new DataSet();
da.Fill(ds, "Employees");
foreach (DataRow dr in ds.Tables[0].Rows)
{
TableRow trow = new TableRow();
foreach (DataColumn dc in ds.Tables[0].Columns)
{
TableCell tcell = new TableCell();
tcell.Controls.Add(new LiteralControl(dr[dc.ColumnName].ToString()));
trow.Cells.Add(tcell);
trow.Attributes["onmouseover"] = "highlight(this, true);";
trow.Attributes["onmouseout"] = "highlight(this, false);";
trow.Attributes["onclick"] = "link('edit.aspx?id=" + dr[0].ToString() + "');";
HttpResponse myHttpResponse = Response;
HtmlTextWriter myHtmlTextWriter = new HtmlTextWriter(myHttpResponse.Output);
trow.Attributes.AddAttributes(myHtmlTextWriter);
Table1.Rows.Add(trow);
}
}
conn.Close();
Currently rated 5.00 by 4 people
Rate Now!
Date Posted:
06 May 2007 20:38
Last Updated:
03 August 2009 07:10
Posted by:
Mikesdotnetting
Total Views to date:
5436
Printer Friendly Version
Comments
30 July 2010 22:12 from Mikesdotnetting
@James
Since I wrote this article over 3 years ago, I have been using jQuery too.



30 July 2010 21:04 from James Piette
I recently implemented similar functionality on a site I'm building using ASP MVC. I was able to do this using CSS and jquery. I also was using an AJAX call to have a table in a left division post the data to the rightDiv (division with id="divRight".
After including jquery, put this script on the top of the page.
<script type="text/javascript">
function linkfunc(url) {
$(divRight).load(url);
}
Then declare the <tr> tag as follows. (replace the stuff in [] to match your controller call.)
tr class="highlight" onclick="linkfunc('<%= Url.Action("[controlleraction]", "[controllername]", new{/*id=model.id*/})%>');">
To have highlighting work, declare this in the .css file
.highlight:hover
{
background-color:yellow
}