Click here to Skip to main content
13,589,943 members
Click here to Skip to main content
Add your own
alternative version

Stats

129.9K views
47 bookmarked
Posted 26 Apr 2003
Licenced

ASP .NET Kick Start Chapter 3: Creating Basic Web Form Pages

, 26 Apr 2003
Rate this:
Please Sign up or sign in to vote.
In this chapter, you learn how to build Web Form Pages.
Sample Image - 0672324768.jpg
Author Stephen Walther
Title ASP .NET Kick Start
PublisherSams
PublishedDec 2002
ISBN 0672324768
Price US 34.99
Pages 624

Creating Basic Web Form Pages

In This Chapter

  • Overview of Web Form Pages

  • Adding Server Controls

  • Handling Events

In this chapter, you learn how to build Web Form Pages. Web Form Pages, unlike standard static HTML pages, can contain dynamic content. You can use Web Form Pages to do such things as validate form data and display and edit database data. Web Form Pages are the most important part of any Web Application that you build with Visual Studio .NET.

In this chapter, you will learn

  • How to create a simple Web Form Page

  • How to add server controls to a Web Form Page

  • How to handle events in a Web Form Page

Overview of Web Form Pages

Although Web Form Pages can contain dynamic content, the foundation of any Web Form Page is standard HTML. You create all the static portions of a Web Form Page by using the same methods that you learned about in Chapter 2, "Using the Visual Studio .NET Designer."

However, Web Form Pages can contain two things that cannot be included in static HTML pages. Web Form Pages can contain server controls and application logic.

You can think of server controls as server-side HTML tags. When you add a server control to a page, the control is executed on your Web server and it generates content that is sent to a Web browser.

The advantage of server controls over plain old HTML tags is that you can program server controls. Server controls have properties, methods, and events that you can manipulate in your code.

In this chapter, you'll be provided with an overview of the basic server controls for building form elements. For example, you'll learn how to add Textbox and Button controls to a Web Form Page.

A Web Form Page can also contain application logic. You can add programming code to a Web Form Page that executes whenever the page is requested. For example, you can write Visual Basic .NET code that retrieves data from a database table and displays the data in a server control.

In this chapter, you'll learn how to add application logic to a Web Form Page that handles different page events. For example, you'll learn how to display different messages on a page depending on the options that a user selects in a form.

Creating a Simple Web Form Page

We'll start with a simple Web Form Page. We'll create a page that randomly displays a fortune.


Note - You should add a Web Form Page to an existing ASP.NET project. To learn how to create a new project, see Chapter 1, "Getting Familiar with the Development Environment."


First, we need to add a Web Form to a project by doing the following:

  1. Select Project, Add Web Form.

  2. In the Add New Item dialog box, enter the name Fortune.aspx for the Web Form in the Name text box.

  3. Click Open.

Now that you've created a Web Form Page, you can add server controls to the page from the Web Forms toolbox. We'll add a Label control to the page by performing the follow steps:

  1. If the Toolbox window is not already open, select View, Toolbox.

  2. Drag a Label control onto the Designer surface from under the Web Forms tab in the Toolbox.

After you add the Label control, your screen should resemble Figure 3.1


Figure 3.1

Adding a Label control to a Web Form Page.

The next step is to add some application logic to the page. We want to retrieve a random fortune from an ArrayList of fortunes and display the fortune in the Label control. To do this, perform the following steps:

  1. Double-click the Designer surface to switch to the Code Editor.

  2. Enter the following code for the Page_Load() method:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
     // Put user code to initialize the page here
     ArrayList colFortunes = new ArrayList();
     Random objRan = new Random();
    
     colFortunes.Add("Good things will happen!");
     colFortunes.Add("Future looks bright!");
     colFortunes.Add("Stay in bed!");
    
     Label1.Text = colFortunes[ objRan.Next( 3 ) ].ToString();
    }

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, _
                          ByValue As System.EventArgs) Handles MyBase.Load
     'Put user code to initialize the page here
     Dim colFortunes As New ArrayList()
     Dim objRan As New Random()
    
     colFortunes.Add("Good things will happen!")
     colFortunes.Add("Future looks bright!")
     colFortunes.Add("Stay in bed!")
    
     Label1.Text = colFortunes(objRan.Next(3))
    End Sub

Finally, we are ready to compile and view our Web Forms page. Right-click the Web Form in the Solution Explorer window and select Build and Browse. The Web Form Page will be opened in a browser and you should see a fortune (see Figure 3.2). Whenever you click the Refresh button, a new fortune is randomly selected and displayed.


Tip - If you receive an error when building your code, select Build Solution from the Build menu. A list of errors in your code will pop up in the Task List window. You can double-click an error to go directly to the error in your code.



Figure 3.2

A Web Form Page displaying a random fortune.

The Two Parts of a Web Form Page

When you create a Web Form Page, you typically need to work with the page by using three different interfaces. While designing the visual elements of a Web Form Page, you use either Design View or HTML View with the Designer. While developing the application logic for a Web Form Page, you use the Code Editor.

In reality, a Web Form Page consists of two files. One file, the presentation page, contains all the user interface elements of the Web Form, such as HTML tags and Web server controls. This file must end with the extension .aspx. This is the page that you actually request when opening the page in your Web browser.

A Web Form also uses a second file, called the code-behind file, which contains all the application logic for the page. By default, the code-behind file does not appear in the Solution Explorer window. To see this file, you must select Show All Files from the Project menu. The code-behind file has the same name as the presentation page with the addition of the extension .cs or .vb. The code-behind file ends with the extension .cs or .vb because it is a C# or VB.NET class file.

While working with the user interface elements of a Web Form, you use either Design or HTML View in the Designer window. To add application logic to a page, you work with the Code Editor. You can switch between the Designer and Code Editor by using any of the following methods:

  • Double-click the Designer surface to switch to the Code Editor.

  • Select Code from the View menu to switch to the Code Editor or select Design from the View menu to switch to the Designer window.

  • Use the keyboard shortcuts Shift+F7 and F7.

  • In the Designer window, right-click the page and select View Code.

  • In the Solution Explorer window, right-click the page and select either View Code or View Designer.

Compiling and Viewing Web Form Pages

Because one part of a Web Form Page is a C# or Visual Basic .NET class file, you must compile a Web Form Page before you can view it in a Web browser. If you don't compile a Web Form before opening the page in a browser, you'll receive the error displayed in Figure 3.3.


Figure 3.3

Error from viewing a Web Form Page without compiling it.

You can compile all the files in a project and view the output of a particular Web Form Page by right-clicking the page in the Solution Explorer window and selecting Build and Browse. The page is compiled and displayed in the default Visual Studio .NET Web browser. This will be the preferred method of compiling and viewing pages used in this book.


Tip - If you prefer to use the keyboard, you can build and browse the current page by pressing Ctrl+F8.


It is important to understand that there is no way to build only a single page in a project. When you do a build, all files contained in the project are compiled. This means that when you have any errors in any page in a project, you cannot build any other page.


Tip - You can temporarily exclude a page from a project by right-clicking the page in Solution Explorer and selecting Exclude From Project. You'll need to do this when the page has an error but you want to work on another page before fixing it. You can recover the excluded page by selecting Show All Files from the Project menu and then right-clicking the filename and selecting Include In Project.


Alternatively, you can build all the files in a solution or project without opening a page in a Web browser. You can select any one of the following options from the Build menu:

  • Build Solution—Compiles all files in all projects contained in the current solution that have been modified since the Build command was last executed

  • Rebuild Solution—Compiles all files in all projects contained in the current solution, regardless of whether the files have been modified since the Build command was last executed

  • Build Project Name—Compiles all files in a particular project that have been modified since the Build command was last executed

  • Rebuild Project Name—Compiles all files in a particular project that have been modified since the Build command was last executed

When you compile the files in a project using any of these methods, an Output window opens that displays messages generated during compilation. At the end of compilation, the Output window should display the number of files that were successfully built.

If any errors are encountered while building a project or solution, the Task window will open and display a list of the errors. You can double-click any error in the Task List to go directly to the page containing the error.


Note - You also can compile the files in your application by using the options located under the Debug menu. Debugging is discussed in detail in Chapter 6, "Debugging Your Web Form Pages."


Adding Server Controls

Unlike standard HTML pages, Web Form Pages can contain Web server controls. Web server controls represent the user interface elements in a page. Unlike normal HTML tags, server controls have properties, methods, and events that you can access within your code.

There are two types of server controls that you can add to a Web Form Page—HTML controls or Web Forms controls.

The HTML controls directly reflect existing HTML tags. For example, there is an HTML control that represents an HTML <form> tag, an HTML control that represents an HTML <table> tag, and so on. You can take an existing HTML document and quickly convert the HTML elements contained in the document into server controls by taking advantage of the HTML controls.

There are more Web controls than HTML controls. The Web controls do not directly reflect existing HTML tags. For example, the DataGrid Web control enables you to display and edit database data and the Calendar control enables you to display an interactive calendar.

In the following sections, you learn how to add both HTML and Web controls to your Web Form Pages.

Using HTML Controls

Within Design View, you can convert any HTML element in a page to an HTML control. To convert an element, right-click the element within Design View and select Run As Server Control. After you convert an HTML element to a server control, it will appear with a green glyph that looks something like a VCR play button (see Figure 3.4).


Figure 3.4

Converting an HTML text field to a server control.

For example, to convert an HTML text field into an HTML control, do the following:

  1. Add a Web Form Page to your project and switch to Design View.

  2. Add a text field to your Web Form Page by double-clicking the Text Field element under the HTML tab on the Toolbox.

  3. Right-click the text field on the Designer surface and select Run As Server Control.

When you added the text field to the Web Form Page in step 2, the following HTML tag was added to the page (you can see this tag by switching to HTML View):

<INPUT type="text">

After you convert the text field to an HTML control, the tag is converted to look like the following:

<INPUT type="text" id=Text1 name=Text1 runat="server">

You should notice that three new attributes are added to the HTML tag: id, name, and runat. The id attribute provides the control with a unique identifier for the page. The name attribute provides the control with a name for the form. Finally, and most importantly, the runat="server" attribute marks the HTML tag as a server control.

When you convert an HTML tag into an HTML control, the tag is automatically converted to one of the following HTML controls:

  • HtmlAnchor Represents a hyperlink tag

  • HtmlButton Represents a button tag

  • HtmlForm Represents a form tag

  • HtmlGenericControl Represents any HTML tag not explicitly represented by another HTML control

  • HtmlImage Represents an image tag

  • HtmlInputButton Represents a submit or reset button

  • HtmlInputCheckbox Represents a check box tag

  • HtmlInputFile Represents a file upload button

  • HtmlInputHidden Represents a hidden form field

  • HtmlInputImage Represents an image button

  • HtmlInputRadioButton Represents a radio button

  • HtmlInputText Represents a text field or password field

  • HtmlSelect Represents a select tag (a drop-down list or list box)

  • HtmlTable Represents a table tag

  • HtmlTableCell Represents a table cell tag

  • HtmlTableRow Represents a table row tag

  • HtmlTextArea Represents a text area

If you convert an image into an HTML control, the image tag is converted into an HtmlImage control. If you convert a tag that does not have a corresponding control, the tag is converted into an HtmlGenericControl. For example, if you convert a <span> tag into a control, the control is represented by the HtmlGenericControl control.

Using Web Controls

Unlike HTML controls, Web Forms controls do not directly correspond to existing HTML controls. You can find all of the Web Forms controls under the Web Forms tab on the toolbar.

The Web Forms controls can be divided into three groups. The first group of Web controls represents basic form and page elements:

  • CheckBox Represents a single check box

  • CheckBoxList Represents a group of multiple check boxes

  • DropDownList Represents a drop-down list of items

  • Hyperlink Represents a hyperlink to a new page

  • Image Represents an image

  • ImageButton Represents an image button

  • Label Represents a label

  • LinkButton Represents a hyperlink that submits a form to the same page

  • Listbox Represents a list box of items

  • Literal Represents static text or HTML in a page

  • Panel Represents a container other controls

  • Placeholder Represents a spot on the page where other controls can be added

  • RadioButton Represents a single radio button

  • RadioButtonList Represents a group of multiple radio buttons

  • Table Represents an HTML table

  • TextBox Represents a single-line, multi-line, or password text box

You'll learn how to use many of the controls in this first group in the following sections of this chapter.

There's also a second group of Web controls that enable you to perform form validation. The following is a list of the controls in this group:

  • CompareValidator Enables you to validate the data in a form field against a fixed value or other form field

  • CustomValidator Enables you to validate the data in a form field by using a custom subroutine

  • RangeValidator Enables you to validate the data in a form field against a minimum and maximum value

  • RegularExpressionValidator Enables you to validate the data in a form field against a regular expression

  • RequiredFieldValidator Enables you to validate the data in a form field by checking whether the form field contains a value

  • ValidationSummary Enables you to display a summary of validation error messages on a page

You'll learn how to validate forms with the validation controls in Chapter 4, "Validating Web Form Pages."

There's a third group of controls that enable you to format, display, and edit data:

  • Repeater Enables you to format items from a data source

  • DataList Enables you to format items from a data source in multiple columns and create interactive menus

  • DataGrid Enables you to format, sort, page through, and edit items from a data source

You'll learn how to take advantage of the data controls in the second part of this book, "Working with Database Data."

Finally, the members of the last group of controls are harder to categorize. The Web controls in this group enable you to perform more specialized tasks:

  • AdRotator Can be used to randomly display banner advertisements

  • Calendar Can be used to display an interactive calendar

  • CrystalReportViewer Can be used to display reports with Crystal Reports

  • Xml Can be used to display XML documents

Adding Label Controls

There are two types of labels that you can add from the Toolbox. You can add an HTML label from the HTML tab or a Label Web Forms control from the Web Forms tab. It's important to not confuse these two types of labels.

A Web Forms Label control, unlike a standard HTML label, enables you to dynamically assign content to an area of a page. For example, you can use a Label control to display the current time, display the number of records in a database table, or display an error when validating a form.

A Label control has one important property—the Text property. In your code, you can assign any text to the Text property that you want. For example, earlier in this chapter, in the "Creating a Simple Web Form Page" section, you assigned a random fortune to a Label control with a line of code that looks like the following:

C#

Label1.Text = colFortunes[ objRan.Next( 3 ) ].ToString();

VB.NET

Label1.Text = colFortunes(objRan.Next(3))

One potentially confusing thing about a Web Forms Label control is that you cannot assign text to it in the same way as you can assign text to an HTML label. If you want to assign text to an HTML label, you can simply double-click the label and type the text. When using a Web Forms Label control, on the other hand, you need to explicitly set the value of the Text property.

For example, suppose that you want to add a Label control to a page that, by default, displays the text "Hello World!". To do so, perform the following steps:

  1. Double-click the Label control under the Web Forms tab to add a Label control to a page.

  2. Select the label from the drop-down list in the Properties window.

  3. Find the Text property in the Properties window and enter the value "Hello World!".

After you complete these steps, the label should display the text "Hello World!".

Adding Button Controls

There are three types of button controls that you can add to a Web Form Page:

  • Button Displays the normal form submit pushbutton

  • ImageButton Displays an image for the button

  • LinkButton Displays a hypertext link for a button

All three types of buttons submit a form and any information it contains back to the Web server. The buttons differ only in their appearance.

For example, suppose that you want to create a page that displays the current time. However, you want to add a button to the page that enables you to refresh the current time whenever it is clicked.

First, you need to add the necessary controls to the Designer surface:

  1. Select Add Web Form from the Project menu. Enter the name RefreshTime.aspx for the page and click Open.

  2. Add a Web Forms Label control to the page by dragging the Label control from under the Web Forms tab on the toolbar onto the Designer surface.

  3. Add a Button control to the page by dragging the Button control from under the Web Forms tab on the toolbar onto the Designer surface.

Next, you need to add code to the Code Editor that executes whenever you click the button:

  1. Double-click the Button control on the Designer surface. Double-clicking the button should switch you to the Code Editor and the cursor should automatically appear within a method named Button1_Click().

  2. Within the Button1_Click() method, enter the following line of code:

    C#

    Label1.Text = DateTime.Now.ToString();

    VB.NET

    Label1.Text = DateTime.Now
  3. Right-click the Web Form Page in the Solution Explorer window and select Build and Browse.

When you have completed these steps, a page similar to the one in
Figure 3.5 should be displayed.


Figure 3.5

Adding a Button control to a Web Form Page.

Adding TextBox Controls

A TextBox Web control represents an HTML text field. However, unlike a standard HTML text field, a TextBox control has properties, methods, and events that you can manipulate in your code.

The most important property of a text box is the Text property. You can use the Text property to assign a default value to a text box in your code. You can also use the Text property to read a value that a user has entered into the text box.

For example, suppse that you want to create a Web Form Page with Label, TextBox, and Button controls. When someone enters text into the text box and clicks the button, the text is copied from the TextBox control to the Label control.

Perform the following steps to add the necessary controls:

  1. Create a new Web Form Page named CopyField.aspx by selecting Add Web Form from the Project menu.

  2. Add a Label control to the page by double-clicking the Label control under the Web Forms tab on the toolbar.

  3. Add a TextBox control to the page by double-clicking the TextBox control under the Web Forms tab on the toolbar.

  4. Add a Button control to the page by double-clicking the Button control under the Web Forms tab on the toolbar.

Next, you need to add the code that executes when you click the Button control:

  1. Double-click the Button control on the Designer surface. Double-clicking the button should switch you to the Code Editor and the cursor should automatically appear within a method named Button1_Click().

  2. Within the Button1_Click() method, enter the following line of code:

    C#

    Label1.Text = TextBox1.Text;

    VB.NET

    Label1.Text = TextBox1.Text
  3. Right-click the Web Form Page in the Solution Explorer window and select Build and Browse.

If you enter text into the TextBox control and click the button, the text should be copied to the Label control (see
Figure 3.6).


Figure 3.6

Copying the value of a TextBox control to a Label control.

A TextBox control can represent a single-line, multi-line, or a password field. To display different types of fields with a TextBox control, you assign different values to the TextBox control's TextMode property. (You can modify the TextMode property in the Properties window.)

By default, the TextMode property has the value SingleLine and a single-line text field is displayed. You specify the width of a single-line text box by assigning a value to the control's Columns property. You can indicate a maximum length for a single-line text box with the MaxLength property. (The maximum length is specified in characters.)

If you assign the value Password to the TextMode property, the text box displays a password field. A password text box works in exactly the same way as a single-line text box except for the fact that any characters entered into the text box are hidden (characters are echoed with asterisks).

Finally, if you assign the value MultiLine to the TextMode property, the text box renders a text area. When creating a multi-line text box, you can assign values to the both the Columns and Rows properties. However, any value assigned to the MaxLength property is ignored.

You can also assign a value to the Wrap property when working with a multi-line text box. When Wrap has the value True, text automatically word wraps within the text box. When Wrap is False, text continues scrolling to the right until you enter a carriage return.

Adding List Controls

You can use any of the following controls to display a list of items:

  • ListBox

  • DropDownList

  • RadioButtonList

  • CheckBoxList

All of the list controls share common properties because they all derive from the base ListControl class. One of the most important of these properties is the Items property. The Items property represents the individual list items displayed by the control.

Suppose, for example, that you want to display a list of products in a ListBox control. Perform the following steps to do so:

  1. Double-click the ListBox control in the Web Forms tab on the Toolbox.

  2. In the Properties window, click the ellipsis that appears next to the Items property.

  3. Click the Add button in the ListItem Collection Editor (see Figure 3.7).

  4. Enter Shaving Cream for the value of the Text property in the ListItem Properties pane of the ListItem Collection Editor.

  5. Click the Add button.

  6. Enter Shampoo for the value of the Text property in the ListItem Properties pane of the ListItem Collection Editor.

  7. Click OK.

  8. Right-click the Web Form Page in the Solution Explorer window and select Build and Browse.


Figure 3.7

The ListItem Collection Editor.

After you complete these steps, the list box will display the two products: Shaving Cream and Shampoo.

All the list controls have a property named SelectedItem that represents the currently selected list item in the list control. You can use SelectedItem.Text to return the Text property of a list item and SelectedItem.Value to return the Value property of a list item. The Text property represents the text that the list control displays, and the Value property represents a hidden value associated with the list item.

Suppose that, after creating a list box that displays a list of products, you want to show the selected item from the list box in a Label control.

Perform the following steps to add the necessary controls:

  1. Create a new Web Form Page named ShowList.aspx by selecting Add Web Form from the Project menu.

  2. Drag the ListBox control from under the Web Forms tab on the Toolbox onto the Designer surface.

  3. Add a couple list items to the ListBox by selecting ListBox in the Properties window and clicking the ellipsis next to the Items property.

  4. Drag the Label control from under the Web Forms tab on the Toolbox onto the Designer surface to add a Label control to your page.

  5. Drag the Button control under the Web Forms tab on the Toolbox onto the Designer surface to add a Button control to your page.

Next, add the code that displays the selected list item:

  1. Double-click the Button control on the Designer surface. This will switch you to the Code Editor and the cursor should appear within the Button1_Click() method.

  2. Enter the following line of code in the Button1_Click() method:

    C#

    Label1.Text = ListBox1.SelectedItem.Text;

    VB.NET

    Label1.Text = ListBox1.SelectedItem.Text
  3. Right-click the Web Form Page in the Solution Explorer window and select Build and Browse.

If you select an item in the list box and click the button, the text of the selected item will appear in the Label control (see Figure 3.8).


Figure 3.8

Displaying the SelectedItem from a ListBox control.

Using the AutoPostBack Property

Several of the Web controls that represent form elements, such as the list controls and the TextBox control, have a special property called the AutoPostBack property. When AutoPostBack has the value True, any change to the control causes the form that contains the control to be automatically posted back to the server.


Caution - The AutoPostBack property uses client-side JavaScript. Older browsers do not support JavaScript, and the AutoPostBack property will fail to function correctly with these browsers.


For example, one common user interface element found in Web applications is a drop-down list used as a navigation menu. When you pick an option in the drop-down list, you are automatically brought to a new page without even clicking a button. Changing the selected item is enough to cause the page to be automatically posted back to the server.

You can create a DropDownList control that automatically posts back to the server by performing the following steps.

First, you need to add the necessary Web Forms controls:

  1. Create a new Web Form Page named AutoPostForm.aspx by selecting Add Web Form from the Project menu.

  2. Drag the DropDownList control from under the Web Forms tab on the Toolbox onto the Designer surface to add a DropDownList control to your page.

  3. In the Properties window, select the DropDownList control and assign the value True to the AutoPostBack property.

  4. In the Properties window open the ListItem Collection Editor dialog box by clicking the ellipsis next to the Items property.

  5. Add a list item with the text Home and the value home.aspx.

  6. Add a list item with the text Products and the value products.aspx.

  7. Click OK to close the ListItem Collection Editor dialog box.

Next, you need to add code that executes whenever a new item is selected in the DropDownList control:

  1. Double-click the DropDownList control on the Designer surface. Doing this will switch you to the Code Editor and add a new method named DropDownList1_SelectedIndexChanged().

  2. Type the following lines of code in the DropDownList1_SelectedIndexChanged() method:

    C#

    Response.Redirect(DropDownList1.SelectedItem.Value);

    VB.NET

    Response.Redirect(DropDownList1.SelectedItem.Value)
  3. In the Solution Explorer window, right-click the Web Form Page and select Build and Browse.

If you change the selected item in the DropDownList control to Products, the Products.aspx page will automatically load. (You'll receive a 404 Not Found error if the Products.aspx page has not been added to your project.)

Grouping Controls with Panels

You can group controls together on a page by using the Panel control. The advantage of grouping controls within Panel controls is that you can hide or display the controls as a single group.

The Panel control has a property named Visible. When the Visible property is assigned the value False, all elements contained in the panel are hidden.

For example, suppose that you want to display one or another set of questions in an HTML form, depending on the answer a user enters for a previous form question. You can place the two separate sets of questions in two Panel controls. You can then selectively hide or display the contents of each Panel control by modifying the Panel control's Visible property.

To hide or display the contents of a Panel control when a Button control is clicked, do the following:

First, you need to add the necessary controls to the page:

  1. Create a new Web Form Page named ShowPanel.aspx by selecting Add Web Form from the Project menu.

  2. Add a Panel control to the Web Form Page by dragging the Panel control located under the Web Forms tab on the Toolbox onto the Designer surface.

  3. Click the Panel control twice on the Designer surface and erase the text "Panel."

  4. Stretch the Panel control on the Designer surface by pulling the handles that appear around the control with your mouse.

  5. Add an HTML label to the Panel control by selecting the label element located under the HTML tab on the Toolbox and dragging the element onto the Panel control on the Designer surface.

  6. Click the HTML Label control on the Designer surface and enter the text "Hello World!".

  7. Add a Button control to the Web Form Page by dragging the Button control located under the Web Forms tab on the Toolbox onto the Designer surface.

Next, you need to add the code that hides or displays the contents of the panel:

  1. Double-click the Button control on the Designer surface. This will switch you to the Code Editor and add a new method named Button1_Click().

  2. Enter the following line of code in the Button1_Click() method:

    C#

    Panel1.Visible = !Panel1.Visible;

    VB.NET

    Panel1.Visible = Not Panel1.Visible
  3. In the Solution Explorer window, right-click the Web Form Page and select Build and Browse.

When you click the button, the text "Hello World!" should disappear. When you click the button again, the text should reappear (see Figure 3.9).


Figure 3.9

Hiding and displaying controls with a Panel control.


Note - A Panel control uses flow layout. Consequently, you cannot precisely position elements within a Panel control. You can, however, add a Grid Layout Panel or a Table to a Panel control when you want to have more control over the layout of the elements within a panel.


In this case, we simply added an HTML Label control to a single panel on a page. However, you can use the same technique to add multiple Panel controls to a page that contain multiple elements, such as TextBox and DropDownList controls.

Formatting Web Controls

All the Web controls share a common set of formatting properties (all the Web controls derive from the base WebControl class). You can use these properties to modify such properties as the font and color of the controls. You can modify the following properties in the Properties window for each control:

  • AccessKey A keyboard shortcut to the control. For example, if you enter the letter A, you can navigate to the control by pressing Alt+A on your keyboard.

  • BackColor The background color displayed behind the control. Modifying this property opens the Color Dialog box that enables you to pick Custom, Web, or System colors.

  • BorderColor The color used for the border of the control. Modifying this property opens the Color Dialog box that enables you to pick Custom, Web, or System colors.

  • BorderStyle The border style used for the control. Possible values include Solid, Dashed, and Groove.

  • BorderWidth The size of the control's border. This value can be specified in pixels or, in the case of more recent browsers, you can specify other units.

  • CssClass The Cascading Style Sheet class to associate with the control.

  • Enabled The state of the control. When Enabled is False, the control appears ghosted on certain browsers such as Microsoft Internet Explorer version 4.0 or later.

  • Font The font used with the control. You can select the name (typeface) and size of the font and whether the font appears in bold, italic, overline, strikeout, or underline.

  • ForeColor The foreground color used with the control. Modifying this property opens the Color Dialog box that enables you to pick Custom, Web, or System colors.

  • Height The height of the control in pixels or, in the case of more recent browsers, you can specify other units.

  • TabIndex The tab index of the control in a group of controls. Modifies the tab order of controls in a form when used with Internet Explorer 4.0 or later.

  • ToolTip The pop-up text message displayed above a control when you hover the mouse over it.

  • Width The width of the control in pixels or, in the case of more recent browsers, you can specify other units.

For example, you can use these properties to create a Panel control with a dashed red border, and a pink background (see
Figure 3.10).


Figure 3.10

Using formatting properties.

You should understand that not all of these properties work with all controls. For example, modifying an ImageButton control's Font property is both harmless and meaningless. Furthermore, many of these properties, such as the AccessKey and TabIndex properties, only work with Internet Explorer version 4.0 and later (these properties are ignored on other browsers).

The values of several of these properties, such as the Width and Height properties, are specified in units. The default unit for these properties is the pixel. For example, if you enter 120 for the width, this value will be interpreted as 120 pixels.

More recent browsers support the following additional units of measurements (Internet Explorer 5.0 and later supports all of these units):

  • cm—Centimeters.

  • em—Size relative to parent element's size. For example, 2em is twice the size of the parent element.

  • ex—Font size relative to the size of the parent font's lowercase x. For example, a font with the size 2ex is twice the size of the lowercase x in the parent font.

  • in—Inches.

  • mm—Millimeters.

  • %—Percentage.

  • pc—A pica represents 12 points.

  • px—Pixels (the default value).

  • pt—Points (1/72 of an inch).

Again, not all properties support all units. Furthermore, not all browsers support all these units.

Handling Events

As you've seen in previous sections, controls in a Web Form Page can raise events. For example, when you click a button, the Button control raises a Click event. Or, when you select a new list item in a ListBox control, the control raises a SelectedIndexChanged event.

A Web Form Page itself can raise events. For example, you can use page events to perform certain actions whenever the page is requested by a browser.

In the following sections, you'll learn how to handle both control and page events.

Handling Control Events

If you want to perform some action whenever an event is raised by a control, you need to add an event handler to your code. An event handler is a method or subroutine that executes when a certain event is raised.

There are two ways you can add event handlers to your code. First, you can double-click a control on the Designer surface. Double-clicking a control will automatically switch you to the Code Editor and add an event handler for the control's default event.

If you need to add an event handler for something other than a control's default event, you'll need to perform different steps, depending on whether you are working with C# or VB.NET.

To add an event handler with C#, you need to select the control from the drop-down list in the Properties window. Next, click the icon at the top of the Properties windows labeled events (the lightning bolt). Clicking the events button will display a list of all the events associated with the control. You can double-click any of the events listed in the properties window to add an event handler for that event.

To add an event handler when working with VB.NET, you need to switch to the Code Editor (select Code from the View menu). Select a control from the Classname drop-down list that appears at the top-left of the Code Editor. If you select an event from the Method Name drop-down list that appears at the top-right of the Code Editor, the corresponding event handler will be automatically added to your code (see
Figure 3.11).


Figure 3.11

Adding an event handler in VB.NET from the Code Editor.

In most cases, the default event is the one with which you'll want to work. For example, if you add a Button control named Button1 to a page and you double-click the button on the Designer surface, the following event handler is added to the Code Editor:

C#

private void Button1_Click(object sender, System.EventArgs e)
{
}

VB.NET

Private Sub Button1_Click(ByVal sender As Object, ByValue As System.EventArgs)
        Handles Button1.Click

End Sub

An event handler always accepts two parameters—an Object parameter and an EventArgs parameter. All event handlers, regardless of the nature of the event, have the same two parameters.

The Object parameter represents the control that raised the event. You might want to associate multiple controls with the same event-handling subroutine. In that case, you could use the Object parameter to identify the control that raised the event.

The System.EventArgs parameter contains additional information about the event that was raised. This parameter is useless in the case of a simple Button control because there is no additional event information to pass to the event-handling subroutine.

An example of a control with a more interesting EventArgs parameter is the ImageButton control. The event handler for an ImageButton Click event looks like the following:

C#

private void ImageButton1_Click(object sender, 
                                System.Web.UI.ImageClickEventArgs e)
{
}

VB.NET

Private Sub ImageButton1_Click(ByVal sender As System.Object, 
    ByValue As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click

End Sub

Notice that the second parameter passed to this event handler is a System.Web.UI.ImageClickEventArgs parameter. This parameter has two properties that you can read in your code—an X property that represents the x coordinate of location where the user clicked and a Y property that represents the y coordinate of where the user clicked.

For example, you can display the values of the X and Y properties by using a Label control as shown in the following:

C#

private void ImageButton1_Click(object sender, 
                                 System.Web.UI.ImageClickEventArgs e)
{
 Label1.Text = "You clicked at the following coordinates:";
 Label1.Text += e.X;
 Label1.Text += " and ";
 Label1.Text += e.Y;

}

VB.NET

Private Sub ImageButton1_Click(ByVal sender As System.Object, _
     ByValue As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click
 Label1.Text = "You clicked at the following coordinates:"
 Label1.Text &= e.X
 Label1.Text &= " and "
 Label1.Text &= e.Y
End Sub

If you add this event handler to your Web Form Page and click the image displayed by the ImageButton, the page in
Figure 3.12 is displayed.


Figure 3.12

Using the ImageClickEventArgs parameter.

Handling Page Events

A Web Form Page itself has several events that you can handle in your code. The most important of these events is the Page_Load event.

When you create a Web Form Page, Visual Studio .NET automatically creates a Page_Load event handler to handle the Page_Load event for you. You can view this event handler by switching to the Code Editor:

C#

private void Page_Load(object sender, System.EventArgs e)
{
 // Put user code to initialize the page here
}

VB.NET

Private Sub Page_Load(ByVal sender As System.Object, _
                      ByValue As System.EventArgs) Handles MyBase.Load
 'Put user code to initialize the page here
End Sub

This Page_Load subroutine is executed every time someone requests the Web Form Page. The Page_Load subroutine is used most often for initializing variables and controls contained in the Web Form Page.

For example, suppose that you want to display the number of days, hours, minutes, and seconds until the new millennium (the year 3001) in a Label control every time a page is requested (see
Figure 3.13).


Figure 3.13

Displaying the number of days until the millennium.

First, you need to create the necessary controls:

  1. Create a new Web Form Page named ShowDays.aspx by selecting Project, Add Web Form.

  2. Add a Label control to the Web Form Page by dragging the Label control located under the Web Forms tab on the Toolbox onto the Designer surface.

Next, you need to add the code that displays the number of days, hours, minutes, and seconds to the next millennium:

  1. Switch to the Code Editor by double-clicking the Designer surface.

  2. Enter the following code for the Page_Load method:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
     TimeSpan objSpan = 
      DateTime.Parse( "1/1/3001" ) - DateTime.Now;
     Label1.Text = String.Format(
      "Only {0} days, {1} hours, {2} minutes, {3} seconds left!", 
      objSpan.Days,
      objSpan.Hours,
      objSpan.Minutes,
      objSpan.Seconds);
    }

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, _
                          ByValue As System.EventArgs) Handles MyBase.Load
     Dim objSpan As TimeSpan
    
     objSpan = _
      DateTime.op_Subtraction(#1/1/3001#, DateTime.Now)
     Label1.Text = String.Format( _
      "Only {0} days, {1} hours, {2} minutes, {3} seconds left!", _
      objSpan.Days, _
      objSpan.Hours, _
      objSpan.Minutes, _
      objSpan.Seconds)
    End Sub
  3. Right-click the page in the Solution Explorer window and select Build and Browse.

After you create this Web Form Page, a countdown to the new millennium is displayed in the Label control every time you refresh the page (click the Refresh button). The countdown is updated within the Page_Load event handler.

The IsPostBack Property

Code located in the Page_Load subroutine executes each and every time a page is requested. Often, this is not what you want. In many cases, you want to execute code only when the page is first requested.

All controls, both HTML controls and Web controls, retain their values between posts back to the same page on the Web server. For example, if you assign text to a Label control and click a Button control to reload the page, the Label control will retain the text when the page is redisplayed.


Note - The ability of controls to retain their values between posts back to the same page is called view state.


The Data controls, such as the Repeater and DataGrid controls, also retain their values between post backs to the server. For example, if you grab data from a database in the Page_Load event handler and assign the data to a DataGrid control, the DataGrid control will automatically retain the data, even if you repeatedly reload the page by clicking a Button control.

Because controls automatically retain their values between post backs to the server, you typically do not need to assign values to the controls each and every time the page is requested. Typically, you want to assign the value only when the page is first requested.

You can detect whether a page is being requested for the first time by using the IsPostBack property. The IsPostBack property has the value False the first time a page is requested and the value True if the page has been submitted back to the server at least once (for example, by clicking a Button or LinkButton control).

For example, suppose that you want to display the current date and time when the page is first requested, but not when the page is posted back to itself.

First, you need to add the necessary controls:

  1. Create a new Web Form Page named DisplayOnce.aspx by selecting Add Web Form from the Project menu.

  2. Add a Label control to the Web Form Page by dragging the Label control from beneath the Web Forms tab on the Toolbox onto the Designer surface.

  3. Add a Button control to the Web Form Page by dragging the Button control from under the Web Forms tab on the Toolbox onto the Designer surface.

  4. Select Code from the View menu to switch to the Code Editor.

Next, you need to add the code to display the current time:

  1. Double-click the Designer surface to switch to the Code Editor.

  2. Enter the following code for the Page_Load() method:

    C#

    private void Page_Load(object sender, System.EventArgs e)
    {
     if (!IsPostBack)
      Label1.Text = DateTime.Now.ToString();
    }

    VB.NET

    Private Sub Page_Load(ByVal sender As System.Object, _
    >                      ByValue As System.EventArgs) Handles MyBase.Load
     If Not IsPostBack Then
      Label1.Text = DateTime.Now
     End If
    End Sub
  3. In the Solution Explorer window, right-click the Web Form Page and select Build and Browse.

When the page is first opened, the current date and time is displayed (see Figure 3.14). However, if you click the Button control, the current date and time are not updated. The IsPostBack property is used in the Page_Load event handler to prevent the Label control from being updated when the page is posted back to the server.


Figure 3.14

Using the IsPostBack property.

Summary

In this chapter, you learned how to create basic Web Form Pages. First, you were provided with an overview of how Web Form Pages work. You learned how to add a new Web Form Page to a project and compile it.

Next, you were given an overview of HTML and Web controls. You learned how to add each type of control to your project.

Finally, you explored the important topic of event-handling in Web Form Pages. You learned how to handle both control and page events by adding event handlers to your code.

 

© Copyright Pearson Education. All rights reserved.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

Share

About the Author

Sams Publishing
United States United States
This member doesn't quite have enough reputation to be able to display their biography and homepage.
Group type: Organisation

1 members


You may also be interested in...

Pro
Pro

Comments and Discussions

 
Generalregarding asp.NET datagrid &amp; webform Pin
sayyedabdulrahim26-Oct-03 23:54
membersayyedabdulrahim26-Oct-03 23:54 
GeneralA waste of the paper its printed on Pin
Marc Clifton27-Apr-03 10:25
memberMarc Clifton27-Apr-03 10:25 
GeneralRe: A waste of the paper its printed on Pin
dog_spawn27-Apr-03 12:16
memberdog_spawn27-Apr-03 12:16 
GeneralAnd why the hell is it listed in the last 10 Updates for MFC/C++ ? Pin
Andreas Saurwein28-Apr-03 0:51
memberAndreas Saurwein28-Apr-03 0:51 
GeneralRe: And why the hell is it listed in the last 10 Updates for MFC/C++ ? Pin
Marc Clifton28-Apr-03 1:17
memberMarc Clifton28-Apr-03 1:17 
GeneralRe: A waste of the paper its printed on Pin
Carlos H. Perez28-Apr-03 16:57
memberCarlos H. Perez28-Apr-03 16:57 
GeneralRe: A waste of the paper its printed on Pin
StormChild1-Feb-04 22:51
memberStormChild1-Feb-04 22:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.180618.1 | Last Updated 27 Apr 2003
Article Copyright 2003 by Sams Publishing
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid