Article

Build Your Own ASP.NET Website Using C# And VB.NET, Chapter 4 - Web Forms and Web Controls

Page: 1 2 3 4 Next

HtmlTextArea

The HtmlTextArea control creates a server-side version of the <textarea> tag.

<textarea cols="60" rows="10" runat="server"></textarea>

We've glanced only briefly over the HTML controls, as they should all be fairly familiar from your experience with HTML. But if you'd like more information on the HTML controls including the properties, methods, and events for each, see Appendix A, HTML Control Reference.

Processing a Simple Form

Now that you have a basic understanding of ASP.NET page structure, the languages VB.NET and C#, and HTML controls, let's put everything together and create a simple ASP.NET application. The application that we will create, in VB.NET and C#, will be a simple survey form that uses the following HTML controls:

  • HtmlForm
  • HtmlButton
  • HtmlInputText
  • HtmlSelect

Let's begin by creating a new file within your favorite code editor. The following code creates the visual interface for the survey:

Example 4.1. SimpleForm.aspx (excerpt)

<html>  
<head>  
…  
</head>  
 
<body>  
<form runat="server">  
 <h2>Take the Survey!</h2>  
 <p>Name:<br />  
 <input type="text" id="txtName" runat="server" /></p>  
 <p>Email:<br />  
 <input type="text" id="txtEmail" runat="server" /></p>  
 <p>Which server technologies do you use?<br />  
 <select id="servermodel" runat="server" multiple="true">  
   <option>ASP.NET</option>  
   <option>PHP</option>  
   <option>JSP</option>  
   <option>CGI</option>  
   <option>Coldfusion</option>  
 </select></p>  
 <p>Do you like .NET so far?<br />  
 <select id="likedotnet" runat="server">  
   <option selected>Yes</option>  
   <option>No</option>  
 </select></p>  
 <p><button id="myButton" OnServerClick="Click" runat="server">  
 Confirm</button></p>  
</form>  
</body>  
</html>

From what we've already covered on HTML controls, you should have a good idea of what this page will look like. All we've done is place some HtmlInputText controls, an HtmlButton control, and an HtmlSelect control inside the obligatory HtmlForm control. Remember, HTML controls are essentially just HTML tags with the runat="server" attribute. When it's complete, the interface will resemble Figure 4.1.

Figure 4.1. Create the interface of the ASP.NET page using HTML controls.

1329_fig1

When users click the button, we'll simply display their responses in their browsers. In a real application, we'd probably be more likely to save this to a database and perhaps show the results as a chart. Whatever the case, we'd access the properties of the HTML controls as shown in the following code:

Example 4.2. SimpleForm.aspx (excerpt)

<script runat="server" language="VB">  
Sub Click(s As Object, e As EventArgs)  
 Response.Write("Your name is: " & txtName.value & "<br />")  
 Response.Write("Your email is: " & txtEmail.value & "<br />")  
 Response.Write("You like to work with: " & servermodel.value & _  
   "<br />")  
 Response.Write("You like .NET: " & likedotnet.value)  
End Sub  
</script>

Example 4.3. SimpleForm.aspx (excerpt)

<script runat="server" language="C#">  
void Click(Object s, EventArgs e) {  
 Response.Write("Your name is: " + txtName.Value + "<br />");  
 Response.Write("Your email is: " + txtEmail.Value + "<br />");  
 Response.Write("You like to work with: " + servermodel.Value +  
   "<br />");  
 Response.Write("You like .NET: " + likedotnet.Value);  
}  
</script>

Just as you've seen with examples from previous chapters, we place our VB.NET and C# code inside a server-side script block within the <head> part of the page. Next, we create a new Click event handler which takes the two usual parameters. Finally, we use the Response object's Write() method to print out the user's responses within the page.

Once you've written the code, you can save your work and test the results from your browser. Enter some information and click the button. What you type in should appear at the top of the page when the button is clicked.

Introduction to Web Forms

With the inception of new technologies, there's always new terminology to master. ASP.NET is no different. With ASP.NET, even the simplest terms that were previously used to describe a Web page have changed to reflect the processes that occur within them. Before we begin to describe the process followed by Web Forms, let's discuss the foundation concept of Web pages.

On the most basic level, a Web page is a text file that contains markup. Web pages are meant to be viewed from a browser window, which parses the file containing markup to present the information to the user in the layout envisaged by the developer. Web pages can include text, video, sound, animations, graphics, and even chunks of "code" from a variety of technologies.

An HTML form, as you learned in the previous sections, is a page that contains one or more form elements grouped together within an HTML <form> tag. Users interact with the various form elements to make certain choices, or provide certain information; this information is then sent to the server for processing upon the click of a submit button. This is useful to us as ASP.NET developers because regular HTML forms have a built-in mechanism that allows forms to be submitted to the server. Once the form has been submitted, some kind of extra technology—in this case, ASP.NET—needs to be present on the server to perform the actual form processing.

In ASP.NET, we call Web pages Web Forms; they contain presentational elements (ASP.NET Web controls) in an HTML form, as well as any code (the processing logic) we've added for the page's dynamic features.

A typical Web Form is shown in Figure 4.2.

Figure 4.2. A Web Form contains code for processing logic and Web controls for presentational purposes.

1329_fig2

The next section looks at the various Web controls and how they may be used within your Web Forms. They're very similar in appearance to HTML, so you shouldn't have any trouble coming to grips with them.

Introduction to Web Controls

As we've just seen, Web Forms allow users to interact with our site using Web controls. With Web controls, Microsoft basically reinvented HTML from scratch. For example, it created two different Web controls that correspond to the two different versions of the HTML <select> tag: a DropDownList control and a ListBox control. This means there isn't a direct one-to-one correspondence between the Web controls and standard HTML tags, as there is with HTML controls. Web controls follow the same basic pattern as HTML tags, but the tag name is preceded by asp: and the name is capitalized using "CamelCasing." Consider the HTML <input> tag, which creates an input text box on screen:

<input type="text" name="username" size="30" />

The equivalent Web control is the TextBox control, and it would look like this:

<asp:TextBox id="username" Columns="30" runat="server">  
</asp:TextBox>

Note that, unlike many HTML tags, Web controls always require a closing tag (the </asp:TextBox> part above). We can also use the shorthand /> syntax if our Web control tag doesn't contain anything between its opening and closing tags. So, we could also write this TextBox like so:

<asp:TextBox id="username" Columns="30" runat="server" />

To sum up, the key points to remember when working with Web controls are:

  • All Web controls must be placed within a <form runat="server">/#epc#/ tag to function properly.
  • All Web controls require id and runat="server" properties to function properly.
  • All Web controls follow the same pattern, but different properties (attributes) are available to different controls.
  • They all start with the asp prefix, followed by a colon.

There are more Web controls than HTML controls, and some offer advanced features that simply aren't available in HTML alone. Controls that we'll discuss in this and future chapters are as follows:

  • basic Web controls (Chapter 4, Web Forms and Web Controls)
  • validation Web controls (Chapter 5, Validation Controls)
  • data controls (Chapter 9, The DataGrid and DataList Controls)
  • user controls (Chapter 16, Rich Controls and User Controls)
  • rich controls (Chapter 16, Rich Controls and User Controls)

Basic Web Controls

The basic Web controls perform the on-screen layout of a Web page, and mirror in many ways the HTML controls that are based on regular HTML. However, they offer some new refinements and enhancements, and should be used in place of HTML whenever possible. In this section, we'll look at the controls in this group, namely:

  • Label
  • TextBox
  • Button
  • Image
  • ImageButton
  • LinkButton
  • HyperLink
  • RadioButton
  • RadioButtonList
  • CheckBox
  • CheckBoxList
  • DropDownList
  • ListBox
  • Panel
  • PlaceHolder

Label

The easiest way to display static text on your page is simply to add the text to the body of the page without enclosing it in any tag. However, if you want to modify the text displayed on a page from ASP.NET code, you can display your text within a Label control. Here's a typical example:

<asp:Label id="lblMessage" Text="" runat="server" />

The following code sets the Text property of the Label control to display the text "Hello World":

Public Sub Page_Load()  
 lblMessage.Text = "Hello World"  
End Sub  
public void Page_Load() {  
 lblMessage.Text = "Hello World";  
}

Reading this Page_Load() handler code, we can see that when the page first loads, the Text property of the Label control with the ID of lblMessage will be set to "Hello World."

TextBox

The TextBox control is used to create on screen a box in which the user can type or read standard text. This Web control can be set to display a standard HTML text input field, an HTML password field, or an HTML text area, using the TextMode property. The following code shows how we might use it in a simple login page:

<p>Username:  
<asp:TextBox id="txtUser" TextMode="SingleLine" Columns="30"  
   runat="server" /></p>  
 
<p>Password:  
<asp:TextBox id="txtPassword" TextMode="Password" Columns="30"  
   runat="server" /></p>  
 
<p>Comments:  
<asp:TextBox id="txtComments" TextMode="MultiLine" Columns="30"  
   Rows="10" runat="server" /></p>

In each of the three instances above, the attribute TextMode dictates the kind of text box to render.

Button

By default, the Button control renders the same form submit button that's rendered by the HTML <input type="Submit"> tag. When a button is clicked, the form containing the button is submitted to the server for processing, and both click and command events are raised. The following code displays a Button control and a Label:

<asp:Button id="btnSubmit" Text="Submit" runat="server"  
   OnClick="WriteText" />  
<asp:Label id="lblMessage" runat="server" />

Notice the OnClick attribute on the control. Unlike the HtmlButton HTML control, OnClick assigns a server-side event handler—there is no need to remember to use OnServerClick. When the button is clicked, the Click event is raised and the WriteText() subroutine is called. The WriteText() subroutine will contain the code that performs the intended function for this button, such as displaying a message for the user:

Public Sub WriteText(s As Object, e As EventArgs)  
 lblMessage.Text = "Hello World"  
End Sub  
public void WriteText(Object s, EventArgs e) {  
 lblMessage.Text = "Hello World";  
}

It's important to realize that most Web controls have events associated with them, and the basic idea and techniques are the same as for the Click event of the Button control.

Image

An Image control places on the page an image that can be accessed dynamically from code; it equates to the <img> tag in HTML. Here's an example:

<asp:Image id="myImage" ImageUrl="mygif.gif" runat="server"  
   AlternateText="description" />

ImageButton

An ImageButton control is similar to a Button control, but it uses an image you supply in place of the typical gray Windows-style button. For example:

<asp:ImageButton id="myImgButton" ImageUrl="myButton.gif"  
   runat="server" />

LinkButton

A LinkButton control renders a hyperlink on your page. From the point of view of ASP.NET code, LinkButtons can be treated in much the same way as buttons, hence the name.

<asp:LinkButton id="myLinkButon" Text="Click Here" runat="server"  
   />

HyperLink

The HyperLink control, which is similar to the LinkButton control, creates a hyperlink on your page. It's simpler and faster to process than LinkButton, but, unlike the LinkButton control, which offers features such as Click events and validation, HyperLink can be used only to click and navigate from one page to the next.

<asp:HyperLink id="myLink" NavigateUrl="http://www.example.com/"  
   ImageUrl="myButton.gif" runat="server">My Link</asp:HyperLink>

The ImageUrl attribute, if specified, causes the control to display a linked image instead of the text provided.

RadioButton

You can add individual radio buttons to your page one by one, using the RadioButton control. Radio buttons are grouped together using the GroupName property. Only one RadioButton control from each group can be selected at a time.

<asp:RadioButton id="radSanDiego" GroupName="City"  
   Text="San Diego" runat="server" />  
<asp:RadioButton id="radBoston" GroupName="City" Text="Boston"  
   runat="server" />  
<asp:RadioButton id="radPhoenix" GroupName="City" Text="Phoenix"  
   runat="server" />  
<asp:RadioButton id="radSeattle" GroupName="City" Text="Seattle"  
   runat="Server" />

The main event associated with RadioButtons is the CheckChanged event; which can be handled with the OnCheckChanged attribute.

RadioButtonList

Like the RadioButton control, the RadioButtonList control represents radio buttons. However, the RadioButtonList control represents a list of radio buttons and uses more compact syntax. Here's an example:

<asp:RadioButtonList id="radlFavColor" runat="server">  
 <asp:ListItem Text="Red" Value="red" />  
 <asp:ListItem Text="Blue" Value="blue" />  
 <asp:ListItem Text="Green" Value="green" />  
</asp:RadioButtonList>

One of the great features of the RadioButtonList is its ability to bind to a data source. For instance, imagine you have a list of employees in a database. You could create a page that binds a selection from that database to the RadioButtonList control, to list dynamically certain employees within the control. The user would then be able to select one (and only one) employee from that list, and our code could determine the choice.

The most useful event produced by RadioButtonList is the SelectedIndexChanged event, to which you can assign a handler with the OnSelectedIndexChanged attribute.

CheckBox

You can use a CheckBox control to represent a choice that can be only a yes (checked) or no (unchecked) value.

<asp:CheckBox id="chkQuestion" Text="I like .NET!" runat="server"  
 />

As with the RadioButton control, he main event associated with a CheckBox is the CheckChanged event; which can be handled with the OnCheckChanged attribute.

CheckBoxList

As you may have guessed, the CheckBoxList control represents a group of check boxes; it's equivalent to using several CheckBox controls in row:

<asp:CheckBoxList id="chklFavDrinks" runat="server">  
 <asp:ListItem Text="Pizza" Value="pizza" />  
 <asp:ListItem Text="Tacos" Value="tacos" />  
 <asp:ListItem Text="Pasta" Value="pasta" />  
</asp:CheckBoxList>

Like the RadioButtonList control, the CheckBoxList control has the capability to bind to a data source, and produces a SelectedIndexChanged event that you can handle with OnSelectedIndexChanged.

DropDownList

A DropDownList control is similar to the HTML <select> tag. The DropDownList control allows you to select one item from a list using a drop-down menu.

<asp:DropDownList id="ddlFavColor" runat="server">  
 <asp:ListItem Text="Red" value="red" />  
 <asp:ListItem Text="Blue" value="blue" />  
 <asp:ListItem Text="Green" value="green" />  
</asp:DropDownList>

As is the case with other collection-based controls, such as the CheckBoxList and RadioButtonList controls, the DropDownList control can be bound to a database, thus allowing you to extract dynamic content into a drop-down menu. The main event produced by this control, as you might expect, is SelectedIndexChanged, handled with OnSelectedIndexChanged.

ListBox

A ListBox control equates to the HTML <select> tag with the size attribute set to 2 or more. The ListBox control allows you to select items from a multiline menu. If you set the SelectionMode attribute to Multiple, the user will be able to select more than one item from the list, as in this example:

<asp:ListBox id="listTechnologies" runat="server"  
   SelectionMode="Multiple">  
 <asp:ListItem Text="ASP.NET" Value="aspnet" />  
 <asp:ListItem Text="JSP" Value="jsp" />  
 <asp:ListItem Text="PHP" Value="php" />  
 <asp:ListItem Text="CGI" Value="cgi" />  
 <asp:ListItem Text="Coldfusion" Value="cf" />  
</asp:ListBox>

Again, because the ListBox control is a collection-based control, it can be dynamically bound to a data source. The most useful event that this control provides is—you guessed it—SelectedIndexChanged, with the corresponding OnSelectedIndexChanged attribute.

Panel

The Panel control functions similarly to the <div> tag in HTML, in that the set of items that resides within the tag can be manipulated as a group. For instance, the Panel could be made visible or hidden by a Button's Click event:

<asp:Panel id="pnlMyPanel" runat="server">  
 <p>Username:  
   <asp:TextBox id="txtUsername" Columns="30" runat="server" />  
 </p>  
 <p>Password:  
   <asp:TextBox id="txtPassword" TextMode="Password"  
       Columns="30" runat="server" /></p>  
</asp:Panel>  
 
<asp:Button id="btnHide" Text="Hide Panel" OnClick="HidePanel"  
   runat="server" />

The code above creates two TextBox controls within a Panel control. The Button control is outside of the panel. The HidePanel() subroutine would then control the Panel's visibility by setting its Visible property to False:

Public Sub HidePanel(s As Object, e As EventArgs)  
 pnlMyPanel.Visible = False  
End Sub  
public void HidePanel(Object s, EventArgs e) {  
 pnlMyPanel.Visible = false;  
}

In this case, when the user clicks the button, the Click event is raised and the HidePanel() subroutine is called, which sets the Visible property of the Panel control to False.

PlaceHolder

The PlaceHolder control lets us add elements at a particular place on a page at any time, dynamically, through code.

<asp:PlaceHolder id="phMyPlaceHolder" runat="server" />

The following code dynamically adds a new HtmlButton control within the place holder.

Public Sub Page_Load()  
 Dim btnButton As HtmlButton = New HtmlButton()  
 btnButton.InnerText = "My New Button"  
 phMyPlaceHolder.Controls.Add(btnButton)  
End Sub  
public void Page_Load() {  
 HtmlButton btnButton = new HtmlButton();  
 btnButton.InnerText = "My New Button";  
 phMyPlaceHolder.Controls.Add(btnButton);  
}

That's it for our quick tour of the basic Web controls. For more information on Web controls, including the properties, methods, and events for each, have a look at Appendix B, Web Control Reference.

If you liked this article, share the love:
Print-Friendly Version Suggest an Article

Sponsored Links