Article
Build Your Own ASP.NET Website Using C# And VB.NET, Chapter 4 - Web Forms and Web Controls
Handling Page Navigation
Links from page to page are what drives the Web. Without linking, the Web would be little more than a simple page-based information source. Links enable us to move effortlessly from page to page with a single click; they bridge the gaps between related ideas, regardless of the boundaries imposed by geography and politics. This section focuses on page navigability using:
- the
HyperLinkcontrol - navigation objects and their methods
Suppose for a minute that you have created a Website that allows your users to choose from a selection of items on one page. You could call this page viewcatalog.aspx. Imagine that you have a second page, called viewcart.aspx. Once users select an item from viewcatalog.aspx, you'd probably want to link them directly to viewcart.aspx so that they can keep track of their orders. To achieve this, we clearly must pass the information from the viewcatalog.aspx page over to the viewcart.aspx page.
Using The HyperLink Control
The HyperLink control creates a simple HTML hyperlink on a page. Once it's clicked, the user is redirected to the page specified by the NavigateUrl property. For instance:
<asp:HyperLink id="hlAddToCart" NavigateUrl="viewcart.aspx"
runat="server" Text="View Cart" />
Here, the NavigateUrl property specifies that this link leads to the page called viewcart.aspx. Figure 4.3 shows how the HyperLink control is rendered in the browser.
Figure 4.3. The HyperLink control renders similar to the anchor tag in the browser.

However, once we've arrived at the new page, it has no way of accessing the information from the first page. If we need to provide the user some continuity of information, we need something else.
Navigation Objects And Their Methods
The previous example rendered a simple control similar to the HTML anchor tag. Once the link is followed, however, we have no record of the previous page or any data it contained (the Web is a stateless technology).
If we wish to pass information from one page to the next, we can use one of the three methods listed below to create the link between the pages:
Response.Redirect()
Navigates to a second page from code. This is equivalent to using the HyperLink control, but allows us to set parameters on the query string dynamically.
Server.Transfer()
Ends the current Web Form and begins executing a new Web Form. This method only works when the user is navigating to a new Web Form page (.aspx).
Server.Execute()
Begins executing a new Web Form while displaying the current Web Form. The contents of both forms are combined in the response sent to the browser. Again, this method only works when the user is navigating to a Web Forms page (.aspx).
The easiest and quickest way to redirect your users from the viewcatalog.aspx page to the viewcart.aspx page would be using Reponse.Redirect():
Sub linkClk(s As Object, e As EventArgs)
Response.Redirect("viewcart.aspx")
End Sub
void linkClk(Object s, EventArgs e) {
Response.Redirect("viewcart.aspx");
}
You could then use the LinkButton control to call this subroutine as follows:
<asp:LinkButton id="lbAddToCart" Text="Add To Cart"
OnClick="linkClk" runat="server"/>
This time, when you click the LinkButton control, the Click event is raised, the subroutine is called, and Response.Redirect() is called with the name of the page we want to link to as a parameter. In this way, we're redirecting to the new page directly from the code, rather than by using a particular tag. This enables us to pass information to the new page in the query string.
The query string is a list of variables and their respective values that we can append to a page's URL, allowing us to retrieve those variables and values from that page's code.
As an illustration, imagine you have a drop-down list that contains the following product information:
<p><asp:DropDownList id="ddlProducts" runat="server">
<asp:ListItem Text="Pants" />
<asp:ListItem Text="Shirt" />
<asp:ListItem Text="Hat" />
<asp:ListItem Text="Socks" />
</asp:DropDownList></p>
<p><asp:LinkButton id="lbAddToCart" Text="Add To Cart"
OnClick="linkClk" runat="server" /></p>
The code you use to handle link clicks will need to find the item selected in the drop-down list and append it to the query string of the URL to which the user is to be redirected, as follows:
Sub linkClk(s As Object, e As EventArgs)
Dim strQueryStr As String = "?Product=" & _
Server.UrlEncode(ddlProducts.SelectedItem.Text)
Response.Redirect("viewcart.aspx" & strQueryStr)
End Sub
void linkClk(Object s, EventArgs e) {
string strQueryStr = "?Product=" +
Server.UrlEncode(ddlProducts.SelectedItem.Text);
Response.Redirect("viewcart.aspx" + strQueryStr);
}
Note the use of the Server.UrlEncode() method, which converts characters not allowed in query string values (e.g. &) to URL-safe character codes (e.g. %26) that the browser will understand. You should always use this method when adding arbitrary values to query strings.
When a user selects an item from the drop-down list and clicks the LinkButton control, the viewcart.aspx page is opened with the selected product appended as a parameter of the query string. This is illustrated in Figure 4.4.
Figure 4.4. Append the selected item to the query string.
![]()
Now that you've passed the product to the viewcart.aspx page, you have to grab it from the query string in the new page. We get hold of variables from the query string by accessing the Request.QueryString collection, like so:
Sub Page_Load()
lblResult.Text = Request.QueryString("Product")
End Sub
void Page_Load() {
lblResult.Text = Request.QueryString["Product"];
}
Here, we simply display the value of the Product query string parameter, as we see in Figure 4.5.
Figure 4.5. Set the text property of the label control within a Page_Load event handler to accept the new parameter value.

Now, when you select a product and add it to the cart, the result is displayed in the redirected page on a label with an id of lblResult. Now sure, a real product catalog and shopping cart has a lot more to it, but in this section we've uncovered an important building block.
Postback
Postback can be confusing to newcomers because, while most ASP.NET developers know what it is, they can't seem to explain it clearly. The topics we've covered so far, like subroutines, functions, and events, are not new to most Web developers. HTML, in combination with client-side JavaScript, has been doing all that for years. ASP.NET is different to this model, though, because it is a server-side, not client-side, technology—events that occur on a page are handled by code running on the server. For this to work, ASP.NET uses the mechanism of postback.
When an event is triggered, for instance, a button is clicked, or an item in a grid is selected, the page is submitted back to the server for processing, along with information about the event and any preexisting data on the page (via view state). We say the page "posts back" to the server. This is a powerful concept to grasp because it is postback that lets us run code on the server rather than on the client's browser, and it is postback that lets our server code know which items within a drop-down list were selected, or what information a user typed into a text box.
But what would happen if you had multiple DropDownList controls that were populated with database data? Users could interact with those DropDownList controls and, in turn, we could set certain options within the page based on what they selected from the drop-down menus. Although this seems like a common task, with traditional ASP it incurred considerable overhead. The problem is that while the data that's bound to the drop-down menu from the database never changes, every time the user selects an item from the drop-down menu and a postback has to be done, the database must be accessed again to rebuild the contents of each drop-down list on the page. However, this is not a problem in ASP.NET.
In ASP.NET we can check for postback with the IsPostBack property, and thus avoid performing any time consuming tasks unnecessarily. IsPostBack is a page-level property—meaning that it's a property of the page itself—and we'd most commonly use it in the Page_Load() event handler to execute code only when the page is first loaded. Consider the following example:
Example 4.4. PostBack.aspx
<html>
<head>
<script runat="server" language="VB">
Sub Page_Load(s As Object, e As EventArgs)
lblMessage1.Text = Now()
If Not IsPostBack Then
lblMessage2.Text = Now()
End If
End Sub
</script>
</head>
<body>
<form runat="server">
<p>Not Checking for postback:<br />
<asp:Label id="lblMessage1" runat="server" /></p>
<p>Checking for postback:<br />
<asp:Label id="lblMessage2" runat="server" /></p>
<p><asp:Button id="btnClick" Text="Click Me" runat="server" />
</p>
</form>
</body>
</html>
Example 4.5. PostBack.aspx
<html>
<head>
<script runat="server" language="C#">
void Page_Load(Object s, EventArgs e) {
lblMessage1.Text = Convert.ToString(DateTime.Now);
if (!IsPostBack) {
lblMessage2.Text = Convert.ToString(DateTime.Now);
}
}
</script>
</head>
<body>
<form runat="server">
<p>Not Checking for postback:<br />
<asp:Label id="lblMessage1" runat="server" /></p>
<p>Checking for postback:<br />
<asp:Label id="lblMessage2" runat="server" /></p>
<p><asp:Button id="btnClick" Text="Click Me" runat="server" />
</p>
</form>
</body>
</html>
The result will look similar to Figure 4.6.
Figure 4.6. The IsPostBack property checks to make sure the user isn't resubmitting the page.

In this example, the IsPostBack check means that the second label doesn't refresh when the Button control is clicked. Similarly, we could use IsPostBack within the Page_Load() subroutine to set up database-driven drop-down menus just once within each user's session, making the online experience smoother, and making our application more scalable. Don't worry if postback seems a bit confusing now—we'll use it more in upcoming chapters, so if it doesn't yet, it should make sense after a few more practical examples.
Formatting Controls with CSS
HTML was deliberately designed to pay little attention to the specifics of how particular items on a page were rendered. It is left up to the individual browser to work out these intricacies, and tailor the output to the limitations and strengths of the user's machine. While we can change font styles, sizes, colors, and so on using HTML tags, this is a practice that can lead to verbose code and pages that are very hard to restyle at a later date.
The Cascading Style Sheets (CSS) language aims to provide the degree of control, flexibility, and pizzazz that modern Web designers seek. It's a standard that's widely supported by all the popular browsers, in its oldest version (CSS1) at the very least.
CSS is a powerful tool for Web developers because it gives us the power to create one set of styles in a single sheet, and apply those styles to all the pages in our Website. All the pages then use the same fonts, colors, and sizes for the same sections, giving the site a consistent feel throughout. Regardless of whether our site contains three pages or three hundred, when we alter the styles in the style sheet, those changes are immediately applied to all pages based on that style sheet.
Types of Styles and Style Sheets
There are three different ways of associating styles to elements of a particular Web page. I've already mentioned the first, and usually the best, which is an external file:
External File
By placing your style rules in an external style sheet, you can link this one file to any Web pages where you want those styles to be used. This makes updating a Website's overall look a cakewalk.
Document Wide
Rather than having an external sheet, you can place style rules for a page within a <style> tag inside that page's head element. The problem is that we can't then use those styles in another page without typing them in again, which makes global changes to the entire site difficult to manage.
Inline
Inline styles allow us to set styles for a single tag using the style attribute. For instance, we might create a text box in regular HTML with a style attribute that draws a border around the text box like so:
<input type="text"
style="border-style:groove" />
CSS style rules create styles that are applied to elements of a page in one of two ways (This is, to some extent, a simplified view of how CSS works. For the complete story, refer to HTML Utopia: Designing Without Tables Using CSS (SitePoint, ISBN 0-9579218-2-9).
Classes
Arguably the most popular way to use styles within your pages, classes allow you to set up a custom style that will be applied to any tag or control that has a class attribute that matches the name of your custom style.
Tag Redefinition
Redefining a tag affects the appearance of certain standard HTML tags. For instance, the <hr> tag is generally given a width of 100% by default, but you could redefine the tag in CSS to have a width of 50%.
Whether you're building external, document-wide, or inline style sheets, properties for classes and tag redefinitions use the same syntax. To create a class within an external style sheet file, you'd use the following syntax:
.myClass {
font-family: arial;
font-size: 10pt;
color: red;
}
This would then be saved in a file with a .css extension, such as styles.css, and linked into the Web Form with the following line in the <head> tag of your document:
<link href="styles.css" rel="stylesheet" />
Similarly, to define a class within a document-wide style sheet, you would use the following syntax:
<head>
<style type="text/css">
.myClass {
font-family: arial;
font-size: 10pt;
color: red;
}
</style>
</head>
When you're using inline styles, use the following syntax:
<span style="font-family: arial; font-size: 10pt; color: red;">My
Stylized Text</span>
For inline styles, simply add all properties to the tag in question with the style attribute. Above, we've used the <span> tag, but the principle remains the same for the other tags.
Now that you have a basic understanding of some of the fundamental concepts behind CSS, let's look at the different types of styles that can be used within our ASP.NET applications.
Style Properties
There are many different types of properties that you can modify using style sheets. Below is a list of the common types:
Font
This category provides you with the ability to format text level elements, including their font face, size, decoration, weight, color, etc.
Background
This category allows you to customize backgrounds for objects and text. Modifying these values gives you control over the color, image, and whether or not you want to repeat an image.
Block
This category allows you to modify the spacing between paragraphs, lines of text, and spaces between text and words.
Box
The box category provides changes and customizations for tables. If you need to modify borders, padding, spacing, and colors on a table, row, or cell, you can modify elements within this category.
Border
This category lets you draw boxes of different colors, styles and thicknesses around page elements.
List
This category allows you to customize the way ordered and unordered lists are created.
Positioning
Modifying positioning allows you to move and position tags and controls freely.
These categories provide a list of what can generally be modified using CSS. As we progress through the book, the many types of properties will become evident.
The CssClass Property
Once you have defined a class in a style sheet (be it external or internal), you'll want to begin associating that class with elements in your Web Forms. You can associate classes with ASP.NET Web controls using the CssClass property. The following example uses classes defined within a document-wide style sheet:
<html>
<head>
<style type="text/css">
.dropdownmenu {
font-family: Arial;
background-color: #0099FF;
}
.textbox {
font-family: Arial;
background-color: #0099FF;
border: 1px solid;
}
.button {
font-family: Arial;
background-color: #0099FF;
border: 1px solid;
}
.text {
font-family: Arial, Helvetica, sans-serif;
font-size: 10px;
}
</style>
</head>
<body>
<form runat="server">
<p class="text">Please select a product:</p>
<p><asp:DropDownList id="ddlProducts" CssClass="dropdownmenu"
runat="server">
<asp:ListItem Text="Shirt" selected="true" />
<asp:ListItem Text="Hat" />
<asp:Listitem Text="Pants" />
<asp:ListItem Text="Socks" />
</asp:DropDownList></p>
<p><asp:TextBox id="txtQuantity" CssClass="textbox" runat="server"
/></p>
<p><asp:Button id="btnAddToCart" CssClass="button" runat="server"
Text="Add To Cart" /></p>
</form>
</body>
</html>