Monday 30 July 2012

Workaround: Calling a JavaScript Function from a HyperLinkField in a GridView or SPGridView

If you place a HyperLinkField in a GridView and link it to a JavaScript function, then it doesn't work properly. The problem is that the URL specified by the HyperLinkField'sNavigateUrl fails to render when you use a JavaScript reference (such as "Javascript:func();") rather than a standard URL.


As a workaround, we can use the RowDataBoundEvent to prepare a proper call to the JavaScript function. To make this work, while assigning the value we should give "Javascript." (with a period) instead of"Javascript:" (with a colon)


void grid_RowDataBound(object sender, GridViewRowEventArgs e)
{
//if it is not DataRow return.
if (e.Row.RowType != DataControlRowType.DataRow)
{
return;
}
//Loop thru the cells changing the "." to ":" in hyperlink navigate URLs
for (int i = 0; i < e.Row.Cells.Count; i++)
{
TableCell td = e.Row.Cells[i];
if (td.Controls.Count > 0 && td.Controls[0] is HyperLink)
{
HyperLink hyperLink = td.Controls[0] as HyperLink;
string navigateUrl = hyperLink.NavigateUrl.ToLower();
hyperLink.NavigateUrl = hyperLink.NavigateUrl.Replace(
hyperLink.NavigateUrl.Substring(
navigateUrl.IndexOf("javascript."), "javascript.".Length),
"javascript:");
}
}
}

No comments:

Post a Comment