ASP.NET 2005 Annoyances #00002 - Gridview HyperLinkFields & Javascript
So this morning I come into work early and I'm in the coding "zone", fixing defects like a machine. I'm, dare I say, en fuego. Then BAM! ASP.NET 2005 puts the smack down on me.
Let's reenact the scenario without using real code or client names. So I wanted to you use EnableSortingAndPagingCallbacks="true" on a gridview since it makes the UI experience so much cleaner without the constant Postbacks each time you sort. One of the columns needed a javascript function. In the old datagrid you could do something like:
<asp:HyperLinkField HeaderText="Fund" DataTextField="itemName" DataNavigateUrlFields="itemName"
DataNavigateUrlFormatString="BLOCKED SCRIPTalert('{0}');" />
Much to my shock and dismay, this does not work in 2005. The obvious work around for this is to use a templated column. Unfornately, you cannot set EnableSortingAndPagingCallbacks="true" with templated columns. Which sucks. So after giving my monitor the middle finger several times, it dawned on me to just use the OnRowDataBound event. Perhaps it would have taken another developed only one showing of the middle finger to come up with a solution, but it took me several to get the creative energy flowing.
Here's what I did: (I just whipped up a sample which may have some syntax errors)
public void myGrid_OnRowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
e.Row.Cells[0].Text = "<a href=\"#\" onclick=\"alert('" + ((DataRowView)e.Row.DataItem)["itemName"] + "');\">Click Me!</a>";
}
}
And then I did the Tiger Woods fist pump.