ASP.NET Workaround: Calling a JavaScript Function from a HyperLinkField in a GridView

If you place a HyperLinkField in a GridView in an ASP.NET page and link it to a JavaScript function, you’ll find that it doesn’t work properly. The problem is that the URL specified by the HyperLinkField’s NavigateUrl fails to render when you use a JavaScript reference (such as "Javascript:func();") rather than a standard URL.

One possible workaround is to create an item template column containing a hyperlink.

As a workaround, however, you can use the RowDataBoundEvent to prepare a proper call to the JavaScript function. To make this work, developers need to type "Javascript." (with a period) instead of "Javascript:" (with a colon) in the designer.

Here’s an example:

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:");      }   }}
Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

The Latest

microsoft careers

Top Careers at Microsoft

Microsoft has gained its position as one of the top companies in the world, and Microsoft careers are flourishing. This multinational company is efficiently developing popular software and computers with other consumer electronics. It is a dream come true for so many people to acquire a high paid, high-prestige job

your company's audio

4 Areas of Your Company Where Your Audio Really Matters

Your company probably relies on audio more than you realize. Whether you’re creating a spoken text message to a colleague or giving a speech, you want your audio to shine. Otherwise, you could cause avoidable friction points and potentially hurt your brand reputation. For example, let’s say you create a

chrome os developer mode

How to Turn on Chrome OS Developer Mode

Google’s Chrome OS is a popular operating system that is widely used on Chromebooks and other devices. While it is designed to be simple and user-friendly, there are times when users may want to access additional features and functionality. One way to do this is by turning on Chrome OS