Learning More About Binding Data to Controls - Hyperlinks
(Page 3 of 4 )
A very common practice is to dynamically create hyperlinks on a web page. As you’ll remember from when you learned HTML, a hyperlink consists of at least two attributes. The first is the text or image that appears on the web page, and the second is the URL that is called when the visitor selects the hyperlink.
In the next example, both attributes are stored in a column of a table and are then bound to a Repeater control in the Page_Load subroutine when the web page is loaded.
Let’s modify the Customers table (see Chapter 11) by inserting the following two columns so that we can use those columns in the next example:
- CustomerCompany CHAR(30)
- CustomerURL CHAR(30)
Statements in the Page_Load subroutine are nearly the same as those you saw earlier in the case of the Repeater control (see the earlier section “The Repeater Control”), except the query returns the CustomerCompany and the CustomerURL from the Customers table.
Statements in the web page are also similar to statements you saw in the web page of the Repeater control, except for the HyperLink control within the ItemTemplate. We assign column names to the Text attribute and to the NavigateURL attribute.
The CustomerCompany column is assigned to the Text attribute, and the CustomerURL column is assigned to NavigateURL. This is called when the visitor selects the hyperlink.
<%@ Import Namespace="System.Data.SqlClient" %>
<Script Runat="Server">
Sub Page_Load
If Not IsPostBack Then
Dim conCust As SqlConnection
Dim cmdSelectRows As SqlCommand
Dim dtrCust As SqlDataReader
conCust = New SqlConnection( "Server=localhost;UID=
MyID;PWD=MyPassword;Database=CustomerContact Data")
cmdSelectRows = New SqlCommand(
"Select CustomerCompany, CustomerURL From Customers",
conCust)
conCust.Open()
dtrCust = cmdSelectRows.ExecuteReader()
hyperLinks.DataSource = dtrCust
hyperLinks.DataBind()
dtrCust.Close()
conCust.Close()
End If
End Sub
</Script>
<html>
<head><title>Hyperlink Data Binding</title></head>
<body>
<form Runat="Server">
<asp:Repeater ID="hyperLinks" Runat="Server">
<ItemTemplate>
<ASP:HyperLink Text='<%# Container.DataItem("CustomerCompany") %>'
NavigateURL='<%# Container.DataItem("CustomerURL") %>' Runat="Server" />
</ItemTemplate>
</asp:Repeater>
</form>
</body>
</html>
Next: Quiz >>
More ASP.NET Articles
More By McGraw-Hill/Osborne
|
This article is excerpted from chapter 12 of ASP.NET 2.0 DeMYSTiFieD, written by Jim Keogh (McGraw-Hill/Osborne; ISBN: 0072261412). Check it out today at your favorite bookstore. Buy this book now.
|
|