<asp:HyperLink> Control

The <asp:HyperLink> control creates a text or graphic link similar to an <a> tag. It is also scriptable to produce dynamic links in response to page events. Its general format is shown below.

<asp:HyperLink id="id" Runat="Server"
  ImageUrl="url"
  NavigateUrl="url"
  Target="_blank|_parent|_self|_search|_top|framename"
  Text="string"
    property="value"...
/>
Figure 4-26. General format for <asp:HyperLink> control.

The linked page is given in the NavigateUrl property. The value can be a relative or absolute URL. The link can be displayed as either text or an image. To display linking text, set the Text property; to display an image, set the ImageUrl property. If both Text and ImageUrl properties are set, the ImageUrl property takes precedence and the Text property serves as a Tool Tip. If the image is unavailable, the Text property is displayed.

A window target or frame name can be coded in the Target property specifying where the linked page is opened. The following special references can be used.

Target Description
_blanka new browser window
_parentthe immediate parent frame of a frameset
_selfthe current frame or window
_searchthe window search pane
_topthe full window outside a frameset
framenamethe name of a frame in a frameset
Figure 4-27. Values for the Target property.

Absence of a Target property opens the linked page in the current window. When linking to remote pages, it is usually preferable to open the page in a new window or in a different frame from the current page. Otherwise, continued navigation from within the linked page can make it difficult for the visitor to return to your original page.

Displaying HyperLinks

The following link is produced with an <asp:HyperLink> control specifying a text link and targeting the page to a new browser window. The URL is the remote path to the page.

Go to Google

Figure 4-28. Using a HyperLink control to target a link.
<asp:HyperLink Runat="Server"
  Text="Go to Google"
  NavigateUrl="http://www.google.com"
  Target="_blank"/>
Listing 4-39. Code to open a HyperLink in a new browser window.

Targeting Frames for HyperLinks

The Target property can identify a frame within which the linked page is displayed. In the following example, an XHTML <iframe> tag is named as the target for a link. The link uses a graphic image.

Go to Google
Figure 4-29. Targeting a HyperLink to a frame.
<asp:HyperLink Runat="Server"
  ImageUrl="google.gif"
  Text="Go to Google"
  NavigateUrl="http://www.google.com"
  Target="SearchFrame"/>

<iframe name="SearchFrame" width="550" height="220"></iframe>
Listing 4-40. Code to target a HyperLink to a frame.

Notice that it is not necessary to convert the <iframe> tag into a server control by supplying an id value or adding Runat="Server". A frame name is sufficient for the Target property. In fact, supplying an id causes the Target assignment not to work properly and to open the page in a separate browser window.

Scripting HyperLink Controls

As a server control, a HyperLink can be scripted. This normally means that URLs can be assigned dynamically to the control. In the following example, enter a valid URL into the text box and click the "Make Link" button. A clickable text link is created for opening the entered URL in a separate browser window.

Enter URL:

Figure 4-30. Scripting a HyperLink control.
<SCRIPT Runat="Server">

Sub Make_A_Link (Src As Object, Args As EventArgs)
  MyURL.NavigateURL = URL.Text
  MyURL.Text = "Go to " & URL.Text
End Sub

</SCRIPT>

<form Runat="Server">

Enter URL: 
<asp:TextBox id="URL" Width="300" Runat="Server"/>
<asp:Button Text="Make Link" OnClick="Make_A_Link" Runat="Server"/>

<asp:HyperLink id="MyURL" Target="_blank" Runat="Server"/>

</form>
Listing 4-41. Code to script a HyperLink control.

A click on the HyperLink's text link opens the URL in a separate browswer window (Target="_blank"). Notice that the control does not have an originally coded NavigateUrl or a Text property. These properties are assigned dynamically by the script.

When the "Make Link" button is clicked, the Make_A_Link subprogram assigns the entered URL (the URL.Text property of the textbox) as the NavigateUrl property of the HyperLink control. The Text property of the HyperLink is also assigned the entered URL as the link text. Although you have not been formally introduced to the <asp:TextBox> control, you should recognize its use from other controls with Text properties.

Creating URL Links from a Data Source

The NavigateUrl property of a HyperLink can be set dynamically from URLs supplied by an external data source. In the following example, URLs are created from the BooksDB.mdb database based on a BookType value entered into a TextBox. The links open the associated pictures in an XHTML <iframe>.

View Database Pictures

Book Type:








Figure 4-31. Dynamic URLs targeted to a frame.

Code for the page layout is shown below. Notice that provision is made for creating up to five HyperLink controls which have id values sequenced from 1 to 5.

<form Runat="Server">

<h3>View Database Pictures</h3>

<asp:Panel style="float:left" Width="300" Runat="Server">
  Book Type: <asp:TextBox id="TypeIn" Width="100" Runat="Server"/>
  <asp:Button Text="Make Links" OnClick="Make_Links" Runat="Server"/>
  <p>
  <asp:HyperLink id="PicLink1" Target="PictureFrame" Runat="Server"/><br/>
  <asp:HyperLink id="PicLink2" Target="PictureFrame" Runat="Server"/><br/>
  <asp:HyperLink id="PicLink3" Target="PictureFrame" Runat="Server"/><br/>
  <asp:HyperLink id="PicLink4" Target="PictureFrame" Runat="Server"/><br/>
  <asp:HyperLink id="PicLink5" Target="PictureFrame" Runat="Server"/><br/>
  </p>
</asp:Panel>
 
<iframe name="PictureFrame" scrolling="no" marginheight="0" marginwidth="0" 
style="border:ridge 3px; width:95px; height:115px"></iframe>
 
</form>
Listing 4-42. Code for dynamic URLs targeted to a frame.

The TextBox, Button, and HyperLinks are enclosed inside a Panel that floats to the left of the page in order to display the frame wrapped to the right. The frame is styled with CSS properties to approximate the picture sizes displayed there. The HyperLinks have no initial Text or NavigateUrl properties, so they do not show up when the page is first opened.

The script for this page opens the database and retrieves all records which have a BookType value matching that of the value entered into the TextBox. These records are iterated. Their BookIDs are used to create paths to the associated pictures which are assigned to the HyperLinks' NavigateUrl properties, while their BookTitles are used to create link text through assignments to the HyperLinks' Text properties.

<%@ Import Namespace="System.Data.OleDb" %>

<SCRIPT Runat="Server">

Sub Make_Links (Src As Object, Args As EventArgs)
  
  Dim DBConnection As OleDbConnection
  Dim DBCommand As OleDbCommand
  Dim DBReader As OleDbDataReader
  Dim SQLString As String
  
  DBConnection = New OleDbConnection( _
    "Provider=Microsoft.Jet.OLEDB.4.0;" & _
    "Data Source=" & Server.MapPath("../Databases/BooksDB.mdb"))
  DBConnection.Open()
  SQLString = "SELECT BookID, BookTitle FROM Books " & _
              "WHERE BookType = '" & TypeIn.Text & "' ORDER BY BookID"
  DBCommand = New OleDbCommand(SQLString, DBConnection)
  DBReader = DBCommand.ExecuteReader()
  Dim Index As Integer = 1
  While DBReader.Read()
    Dim FoundLink As HyperLink = FindControl("PicLink" & Index)
    FoundLink.NavigateUrl = "../BookPictures/" & DBReader("BookID") & ".jpg"
    FoundLink.Text = DBReader("BookTitle")
    Index += 1
  End While
  DBReader.Close()
  DBConnection.Close()
End Sub

</SCRIPT>
Listing 4-43. Script for dynamic URLs targeted to a frame.

Dynamic References

The trick is in locating the five HyperLink controls for assignments to their NavigateUrl and Text properties. While the script loop is iterating through the records of the returned recordset, it must also identify the appropriate HyperLink control to which to make these assignments. For instance, the first time through the loop the assignments are made to PicLink1; the second time through the loop the assignments are to PicLink2; the third time through the loop the assignments are to PicLink3; and so forth. Therefore, a means is needed to change the target of the assignments on each iteration.

Note that the id values of the HyperLinks include the appended integers 1 - 5. This makes it easy to change references to the controls by appended one of these integers to the string "PicLink". That is, inside the WHILE loop that iterates the recordset, HyperLink ids can be contructed in the following fashion.

Dim Index As Integer = 1
While DBReader.Read()
  Create reference to id "PicLink" & Index
  ...
  Index += 1
End While
Listing 4-44. Dynamically constructing id references.

An integer variable—Index in this example—is initialized to 1. Inside the loop, this value is concatenated to the string "PicLink" to create the initial reference "PicLink1". At the close of the loop, the variable is incremented by 1, so on the next iteration the reference is to "PicLink2", and so on for a many records as contained in the recordset. These incrementing id references, then, can be used to identify the different HyperLink controls to which NavigateUrl and Text assignments are made when iterating the recordset.

Finding Page Controls

Unfortunately, direct property assignments to a control identified with a composed id value cannot be made. It is invalid, for example, to make the following URL and text link assignments for the HyperLink controls, although "logically" this is what needs to happen.

Dim Index As Integer = 1
While DBReader.Read()
  "PicLink" & Index.NavigateUrl = "../BookPictures/" & DBReader("BookID") & ".jpg"
  "PicLink" & Index.Text = DBReader("BookTitle")
  Index += 1
End While
Listing 4-45. Invalid references to dynamic control ids.

Instead, controls whose id values are dynamically created must be "found" on the page using the page's FindControl() method. This method, whose general formats are shown in Figure 4-32, can be used to locate any control on a page.

Dim variable As type
variable = [Page.]FindControl(id)

or

Dim variable As type = [Page.]FindControl(id)
Figure 4-32. General format for FindControl() method.

A script variable is declared as an object type matching that of the control to be found. This variable is then assigned as a reference to a control located on the basis of its id value. This value can be an actual id value coded in the control or it can be an expression deriving an id from from fixed text and other values. The prefix Page. is optional and is assumed if missing.

In the example script, id values for HyperLink controls are derived by the concatenation "PicLink" & Index. This expression produces one of the HyperLink ids and is used in the FindControl() method to locate the HyperLink and assign it to control reference FoundLink.

Dim Index As Integer = 1
While DBReader.Read()
  Dim FoundLink As HyperLink = FindControl("PicLink" & Index)
  FoundLink.NavigateUrl = "../BookPictures/" & DBReader("BookID") & ".jpg"
  FoundLink.Text = DBReader("BookTitle")
  Index += 1
End While
Listing 4-46. Locating a HyperLink control and setting its properties.

Variable FoundLink is declared as a HyperLink control since this is the type of control to be found. It becomes the surrogate for the control located through the FindControl("PicLink" & Index) method, and through this surrogate the original control's NavigateUrl and Text properties are set. These properties are given by values of the BookID and BookTitle fields in the database.

Assignment of the book title field—DBReader("BookTitle")—is directly to the Text property of the control. The value assigned to the NavigateUrl property, however, must be composed as the appropriate path to the picture. In this case, the path is a concatenation of three elements:

"../BookPictures/"  - the relative directory path to the picture &
DBReader("BookID")  - the name of the picture (the same as the BookID) &
".jpg"              - the image extension

For the record with a BookID value of "DB111", then, the concatenation is

  "../BookPictures/" & "DB111" & ".jpg"

resulting in the path "../BookPictures/DB111.jpg". This NavigateUrl is targeted to the frame which displays the picture.

Matching Records with Controls

In the example application there are five records of each BookType to match the five HyperLink controls. What happens if there are fewer or greater number of records returned by the script? With a fewer number of records, the application works just as well. The result is that fewer than five HyperLinks have their NavigateUrl and Text properties set, and fewer than five are displayed.

With greater than five records returned, a problem occurs. The script attempts to "find" HyperLink controls PicLink6, PicLink7, PicLink8, etc., and these do not exist. A script error results. However, the problem is easily solved. Recode the SELECT statement to retrieve only as many records as there are HyperLink controls. Use the TOP n clause to limit the number of records returned to the number of controls available for their display.

SQLString = "SELECT Top 5 BookID, BookTitle FROM Books " & _
            "WHERE BookType = '" & TypeIn.Text & "' ORDER BY BookID"
Listing 4-47. Selecting a fixed number of records from a database.

A more generally useful approach to providing the number of controls needed to correspond with an unknown number of items drawn from a database is to create the controls themselves dynamically, through script. That is, rather than hard-coding a fixed number of HyperLinks on a page, a script can create as many HyperLinks as needed to match the number of book types found in the database. In this case, there is no need to retrieve only as many records as there are hard-coded controls to display them. Creating dynamic controls is taken up in a later tutorial.