Lesson 1: Using Controls

Lesson 1: Using Controls

Controls are the tools for all of the tasks you perform on a Web form. They define the appearance of the form and provide a way to get information and perform tasks on behalf of the user.

Microsoft Visual Studio .NET includes two types of controls that you can use on a Web form and two ways to position those controls on the form. In this lesson, you ll learn about these differences and how they relate to major programming tasks.

After this lesson, you will be able to

  • Select a layout style for your Web form based on the type of application you are creating

  • Explain the differences between server controls and HTML controls and select the appropriate type of control for a particular programming task

  • Bind control values to data items, such as variables, in your application

  • Create templates for controls that contain repeating items

  • Write code to respond to user events on controls

  • Receive files uploaded from a client and store them on the server

Estimated lesson time: 60 minutes

Selecting a Layout

When you draw controls on a Web form, you have two options for how those controls are arranged:

  • Grid layout

    This is the default. Controls are placed exactly where you draw them, and they have absolute positions on the page. Use grid layout for Microsoft Windows style applications, in which controls are not mixed with large amounts of text. Pages using grid layout will not always display correctly in non-Microsoft browsers.

  • Flow layout

    This layout positions controls relative to other elements on the page. If you add elements at run time, the controls that appear after the new element move down. Use flow layout for document-style applications, in which text and controls are intermingled.

To set how controls are placed on a page:

  1. In the Design window, select the Web form.

  2. In the Properties window, select the DOCUMENT object.

  3. Set the DOCUMENT object s pageLayout property to FlowLayout or GridLayout.

Figure 4-1 shows the difference between GridLayout and FlowLayout on a Web form. You use GridLayout for Web forms that have a fixed appearance. You use FlowLayout for Web forms that incorporate text and controls.

figure 4-1 selecting a layout

Figure 4-1. Selecting a layout

When you create controls with GridLayout, Visual Studio adds style attributes to each control that set the position of the control, as shown in boldface in the following form definition:

<form action="webform1.aspx" method="post"  enctype="multipart/form-data" runat="server" > <h2> Upload and View Files on Server </h2> <INPUT  style="Z-INDEX: 101; LEFT: 86px; WIDTH: 347px; POSITION: absolute; TOP: 20px; HEIGHT: 27px" runat="server"  type="file" size="38"> <asp:Button  style="Z-INDEX: 102; LEFT: 357px; POSITION: absolute; TOP: 60px" runat="server" Text="Upload"  Width="74px" Height="31px"></asp:Button> <asp:ListBox  style="Z-INDEX: 103; LEFT: 86px; POSITION: absolute; TOP: 79px" runat="server" Height="140px"  Width="168px"></asp:ListBox> <asp:Button  style="Z-INDEX: 104; LEFT: 268px; POSITION: absolute; TOP: 178px" runat="server" Height="31px"  Width="76px" Text="View"></asp:Button> <asp:Image  style="Z-INDEX: 106; LEFT: 441px; POSITION: absolute; TOP: 24px" runat="server"  Height="132px" Width="162px"></asp:Image> </form>

When you create controls with FlowLayout, Visual Studio omits the style attribute. You can also create controls by double-clicking the control in the Toolbox, instead of using the drag-and-drop operation. Using FlowLayout makes it easier to mix controls and text on a Web form, especially when you re editing the form s HTML source, as shown in following form definition:

<form  method="post" runat="server"> <h2> File Manager </h2> <p> To create a new file, type the name of the file below and click New. </p> <asp:Literal  runat="server"></asp:Literal> <asp:TextBox  runat="server" width="191px"> </asp:TextBox> <asp:Button  runat="server" Width="62px" Height="29px"  Text="New"></asp:Button> <p> To edit a file, select the file from the list below and click Edit. Click Delete to delete the selected file. </p> <asp:Literal  runat="server"></asp:Literal> <asp:ListBox  runat="server" Width="252px"  Height="161px"></asp:ListBox> <br> <asp:Button  runat="server" Width="62" Height="29"  Text="Edit"></asp:Button> &nbsp;&nbsp; <asp:Button  runat="server" Width="62px" Height="29px"  Text="Delete"></asp:Button> </form>

Choosing the Right Control

You can use server controls or HTML controls on a Web form. What s the difference? Basically, server controls are a superset of HTML controls and offer the advantages described in Table 4-1.

Table 4-1. Server Controls vs. HTML Controls

Feature

Server controls

HTML controls

Server events

Trigger control-specific events on the server.

Can trigger only page- level events on server (postback).

State management

Data entered in a control is maintained across requests.

Data is not maintained; must be saved and restored using page-level scripts.

Adaptation

Automatically detect browser and adapt display as appropriate.

No automatic adaptation; must detect browser in code or write for least common denominator.

Properties

The Microsoft .NET Framework provides a set of properties for each control. Properties allow you to change the control s appearance and behavior within server-side code.

HTML attributes only.

So why use anything other than server controls? Because HTML controls have a one-to-one correspondence with standard HTML elements, they provide more direct control over what appears on a page. You use HTML controls for the following reasons:

  • Migration from earlier versions of Active Server Pages (ASP).

    You can load an ASP application into Visual Studio and revise it gradually, rather than rewrite it completely. Earlier versions of ASP supported only HTML elements, and these elements become HTML controls when you load the project in Visual Studio .NET.

  • Not all controls require server-side events or state management.

    This is particularly true when you re doing data binding. Bound items are usually refreshed from the data source with each request, so it s more efficient not to maintain state information for bound controls. This means that you can use HTML controls or turn off state management for bound server controls.

  • You have complete control over what is rendered with HTML controls.

    ASP.NET adjusts the appearance of server controls based on the browser making the request. HTML controls are not adjusted, so you have direct control over their appearance.

Server and HTML controls provide overlapping functionality. In general, it is easier to work with server controls. Table 4-2 lists the server controls and HTML controls by programming task.

Table 4-2. Server and HTML Controls by Programming Task

Task

Server controls

HTML controls

Display text

Label, TextBox, Literal

Label, Text Field, Text Area, Password Field

Display tables

Table, DataGrid

Table

Select from list

DropDownList, ListBox, DataList, Repeater

List Box, Dropdown

Perform commands

Button, LinkButton, ImageButton

Button, Reset Button, Submit Button

Set values

CheckBox, CheckBoxList, RadioButton, RadioButtonList

Checkbox, Radio Button

Display images

Image, ImageButton

Image

Navigation

Hyperlink

none (use <a> tags in text)

Group controls

Panel, Placeholder

Flow Layout, Grid Layout

Work with dates

Calendar

none

Display ads

AdRotator

none

Display horizontal rules

Literal

Horizontal Rule

Get filenames from client

none

File Field

Store data on page

(provided by state management)

Input Hidden

Validate data

RequiredFieldValidator, CompareValidator, RangeValidator, RegularExpressionValidator, CustomValidator,ValidationSummary

none (use page- level scripts)

The following sections describe the major programming tasks you perform with controls to create a user interface.

Working with Text

There are a lot of ways to display text on a page. For read-only text, you can write directly to the Response object, as in Response.Write( Some text ); you can use a Label control; you can use a TextBox control and set its ReadOnly property to True; or you can use a Literal control and compose the text in HTML as you would with the Response.Write method.

To display editable text, however, you want to use a TextBox server control. The TextBox control has the key properties listed in Table 4-3.

Table 4-3. TextBox Control Properties

Property

Use to

Text

Get or set the data in the TextBox control.

TextMode

Display SingleLine, MultiLine (scrollable), or Password text. When set to Password, the text box displays dots in place of the characters typed.

ReadOnly

Prevent the user from changing the text.

AutoPostBack

When set to True, causes the TextBox control to fire a TextChanged postback event when the user leaves the TextBox control after changing the contents. By default, this property is set to False and the Text Changed event is cached until some other postback event occurs.

To see the text controls in action, perform the following steps to create a logon page:

  1. Start a new Web application with two Web forms named Webform1 and Webform2.

  2. On Webform1, draw Label, TextBox, and Button controls, and set their properties to the values shown in the following table:

    Control

    Property

    Setting

    Label1

    Text

    Username:

    Label2

    Text

    Password:

    TextBox1

    ID

    txtUser

    TextBox2

    ID

    txtPassword

    TextMode

    Password

    Button1

    ID

    butOK

    Text

    OK

  3. Add the following code to the butOK_Click event procedure:

    Visual Basic .NET

    Private Sub butOK_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butOK.Click If txtUser.Text = "Guest" And txtPassWord.Text = "Moondog" Then Response.Redirect("Text2.aspx") Else txtPassword.Text = "" End If End Sub

    Visual C#

    private void butOK_Click(object sender, System.EventArgs e) { if ((txtUser.Text == "Guest") && (txtPassword.Text == "Moondog")) Response.Redirect("Text2.aspx"); else txtPassword.Text = ""; }

  4. Run the application. When you enter the username and password specified in the code, Text2 is displayed, as shown in Figure 4-2. Notice that setting the TextMode property to Password causes each character entered to be replaced with a symbol.

    figure 4-2 web forms text1 and text2

    Figure 4-2. Web forms Text1 and Text2

Of course, it s usually not a good idea to put passwords and usernames in code. Instructions on how to save and retrieve passwords from a secure file on the server are included in Chapter 8, Maintaining Security.

Working with Tables and Lists

Text displayed in Label and TextBox controls is arranged in a single block. To arrange text in rows and columns, you need to use one of the list or table controls described in Table 4-4. Use the ListBox, DropDownList, and Table controls for simple dynamic tables and lists. Use the DataGrid, DataList, and Repeater controls for complex tables and lists that contain other controls or are bound to data.

Table 4-4. ASP.NET List and Table Controls

Control

Use to

ListBox

Display read-only text in a simple scrollable list format.

DropDownList

Display read-only text in a simple drop-down list format.

Table

Display text and controls in columns and rows. Table controls allow you to dynamically build tables in code using TableRows and TableCells collections.

DataGrid

Display text and controls in columns and rows using a template to control appearance. DataGrid controls have built-in formatting, sorting, and paging capabilities.

DataList

Display rows of text and controls using a template to control appearance. DataList controls have built-in formatting and selection capabilities.

Repeater

Display rows of other controls using a template to control appearance. Repeater controls do not include the built-in capabilities found in the DataGrid and DataList controls.

Adding Items to a List or Table at Design Time

The ListBox, DropDownList, and Table controls allow you to add static items at design time using the Collection Editor dialog box, as shown in Figure 4-3.

figure 4-3 the collection editor

Figure 4-3. The Collection Editor

You use the Collection Editor to add static items to a ListBox, DropDownList, or Table control, as follows:

  • To add static items to a ListBox or DropDownList control, select the Items property in the Properties window and click the button next to (Collection).

  • To add static items to a Table control, select the Rows property in the Properties window and click (Collection).

Adding Items to a List or Table at Run Time

To add items to a list at run time, use the Add method of the control s Items collection. For example, the following code adds items entered in a TextBox control to ListBox and DropDownList controls:

Visual Basic .NET

Private Sub butAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butAdd.Click ListBox1.Items.Add(txtSource.Text) DropDownList1.Items.Add(txtSource.Text) End Sub

Visual C#

private void butAdd_Click(object sender, System.EventArgs e) { ListBox1.Items.Add(txtSource.Text); DropDownList1.Items.Add(txtSource.Text); }

Both the ListBox control and the DropDownList control automatically store the items you add to them at run time. The Table control, however, will automatically store data only for the table cells created at design time in the Collection Editor. To create additional table rows and cells at run time, you need to rebuild the table from information stored in a state variable. For example, the following code displays comma-delimited items entered in a text box as cells in a table, adding rows to the table each time the user clicks the Add button:

Visual Basic .NET

Private Sub butAdd_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butAdd.Click ' Add text to the page's ViewState. ViewState.Add(Viewstate.Count, txtSource.Text) ' Rebuild the table. RebuildTable() End Sub Private Sub RebuildTable() Dim iCount1, iCount2 As Integer Dim arrWords As String() Dim strWords As String ' For each string saved in ViewState... For iCount1 = 0 To ViewState.Count - 1 ' Create a new table row. Dim rowNew As New TableRow() ' Get the string from ViewState. strWords = ViewState(iCount1) ' Break item list into an array. arrWords = Split(strWords, ",") ' For each item in the array. For iCount2 = 0 To UBound(arrWords) ' Create a new table cell. Dim celNew As New TableCell() ' Set the text to display in the cell. celNew.Text = arrWords(iCount2) ' Add the cell to the table row. rowNew.Cells.Add(celNew) Next ' Add the row to the table. Table1.Rows.Add(rowNew) Next End Sub

Visual C#

private void butAdd_Click(object sender, System.EventArgs e) { ListBox1.Items.Add(txtSource.Text); DropDownList1.Items.Add(txtSource.Text); // Add text to the page's ViewState. ViewState.Add(ViewState.Count.ToString(), txtSource.Text); RebuildTable(); } private void RebuildTable() { string[] arrWords; string strWords; TableRow rowNew; TableCell celNew; // For each string saved in ViewState. for (int iCount1 = 0; iCount1 < ViewState.Count; iCount1++) { char[] strSep = {','}; // Create a new table row. rowNew = new TableRow(); // Get the string from ViewState. strWords = ViewState[iCount1.ToString()].ToString(); // Break the item list into an array. arrWords = strWords.Split(strSep); // For each item in the array. for (int iCount2 = 0; iCount2 <= arrWords.GetUpperBound(0); iCount2++) { // Create a new table cell. celNew = new TableCell(); // Set the text to display in the cell. celNew.Text = arrWords[iCount2]; // Add the cell to the table row. rowNew.Cells.Add(celNew); } // Add the row to the table. Table1.Rows.Add(rowNew); } }

Getting the Selected Item from a List

Use the SelectedItem property to get the current selection from a list. For example, the following code displays the items selected from a list box in a label on a Web form:

Visual Basic .NET

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Test if there is a selected item. If Not IsNothing(ListBox1.SelectedItem) Then ' Display the selected item. Label1.Text = "The selected item is: " _ & ListBox1.SelectedItem.Text Else Label1.Text = "No item is selected." End If End Sub

Visual C#

private void Page_Load(object sender, System.EventArgs e) { // Test if an item is selected. if (ListBox1.SelectedItem == null) Label1.Text = "No item is selected."; else // Display the selected item. Label1.Text = "The selected item is: " + ListBox1.SelectedItem.Text; }

If an item is selected, the SelectedItem property returns a ListItem object; otherwise, SelectedItem returns Nothing or null. Therefore, you should always check the value of SelectedItem before using the returned object s properties.

Using Simple Data Binding with Lists

Controls can get their values from any data source in your application. Data sources can be any public data whether the data is a database table, an array, a property of an object, or an expression combining several items. At its simplest level, data binding provides an easy way to initialize the values of ListBox and DropDownList controls on a Web form.

To see how simple data binding works, follow these steps:

  1. Create a Web form with a DropDownList control and the following code:

    Visual Basic .NET

    ' Public data item for DropDownList. Public arrData As String() = {"This", "that", "and", _  "the", "other"} Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Bind data to controls on this page. Page.DataBind() End Sub

    Visual C#

    // Public data item for DropDownList public string[] arrData= {"This", "that", "and", "the",  "other"}; private void Page_Load(object sender, System.EventArgs e) { Page.DataBind(); }

  2. Select the DropDownList control, and click the button in the DataBindings property in the Properties window. Visual Studio displays the DataBindings dialog box, as shown in Figure 4-4. You use the DataBindings dialog box to load items from any public data source to list or table controls.

    figure 4-4 the databindings dialog box

    Figure 4-4. The DataBindings dialog box

  3. Select the DataSource property in the Bindable Properties list, and then select the Custom Binding Expression option button, type arrData in the expression box, and click OK. When you run the application, the items in the arrData array are displayed in the DropDownList control, as shown in Figure 4-5.

    figure 4-5 binding a list control to an array

    Figure 4-5. Binding a list control to an array

When you use data binding with a server control, you can turn off state management for that control. This improves performance because the DataBind method replaces the automatic view state management provided by ASP.NET.

To turn off state management for a server control, set the control s EnableViewState property to False.

Adding Items to DataGrid, DataList, and Repeater Controls

Use data binding to add items to the DataGrid, DataList, and Repeater controls. These three controls use templates to define their appearance at run time. A template is a set of HTML elements or server controls, or both, that will be repeated for each data item in the control.

To add items to a DataGrid, DataList, or Repeater control, follow these steps:

  1. Define the data source.

  2. Draw the DataGrid, DataList, or Repeater control and bind to the data source.

  3. Edit the templates in the control to add HTML elements or server controls that will be repeated within the list or grid.

  4. Set the properties of the server controls contained in the list or grid to bind to data items in the container s data source.

The following example shows how to add template columns to a DataGrid control and how to bind the controls in those columns to a simple data source:

  1. Create a public data source in your application as you did in the previous procedure. For example, the following code creates an array to demonstrate a simple data source:

    Visual Basic .NET

    ' Public data item for DataGrid. Public arrData As String() = {"This", "that", "and", _  "the", "other"}

    Visual C#

    // Public data item for DataGrid. public string[] arrData = new string[] {"This", "that",  "and", "the", "other"};

  2. Draw a DataGrid control on a Web form.

  3. Add template columns to the control by selecting the DataGrid control and then clicking the Property Builder link at the bottom of the Properties window. Visual Studio displays the Properties dialog box, as shown in Figure 4-6.

    figure 4-6 properties dialog box

    Figure 4-6. Properties dialog box

  4. In the Properties dialog box, select Columns, and then select Template Column in the Columns list and click the Add (>) button to add a template column to the DataGrid control. For this example, add two template columns and click OK.

  5. In the Properties window, select the DataSource property and specify the data source for the control. For this example, type arrData, the array created in step 1.

  6. Create the template used to display data in the control: right-click the DataGrid control, point to Edit Template, and select Columns[0] from the shortcut menu. The control s appearance changes to Edit mode, as shown in Figure 4-7.

    figure 4-7 adding controls to datagrid

    Figure 4-7. Adding controls to DataGrid

  7. Draw other controls on the Web form, and then drag them onto the template to add them to the DataGrid control. For this example, draw a TextBox control and drag it on to the template for column 0.

  8. In the Properties window, select the DataBindings property of the control you just added to the template, and click the button that appears. Visual Studio displays the DataBindings dialog box, as shown in Figure 4-8.

    figure 4-8 the databindings dialog box

    Figure 4-8. The DataBindings dialog box

  9. In the Bindable Properties list, select the property to receive the data item. For this example, select Text. Select Simple Binding, and then expand Container and select DataItem to specify which data item to put into the selected property. Click OK to close the dialog box.

  10. Edit the second template column. To do this, right-click the DataGrid control, select Edit Template, and then select Columns[1] from the shortcut menu.

  11. Repeat steps 4 through 7 for Column(1). For this example, draw a Button control and drag it onto the Column(1) template in the DataGrid control.

  12. Close the template when you ve finished. To do this, right-click the template and select End Template Editing from the shortcut menu. Visual Studio displays the contained controls, as shown in Figure 4-9. To change any of the contained control s properties, edit the template as we did in the preceding steps.

    figure 4-9 the bound controls

    Figure 4-9. The bound controls

Performing Commands

The Button, LinkButton, and ImageButton server controls all trigger postback events to perform commands. A postback event begins a request from the browser, causing the server to process the page s events. The Click event procedure for a button control is processed after any validation or cached events on a page.

To see the order of page events, place a TextBox control, a ListBox control, and a Button control on a Web form and add the following code:

Visual Basic .NET

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Response.Write("Page load.<br>") ' Add items to list box the first time the page loads. If Not IsPostBack Then ListBox1.Items.Add("This") ListBox1.Items.Add("That") ListBox1.Items.Add("The other") End If End Sub Private Sub TextBox1_TextChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles TextBox1.TextChanged Response.Write("Text changed.<br>") End Sub Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged Response.Write("Item selected.<br>") End Sub Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Response.Write("Button clicked.<br>") End Sub

Visual C#

private void Page_Load(object sender, System.EventArgs e) { Response.Write("Page load.<br>"); // Add items to list box the first time the page loads. if (!IsPostBack) { ListBox1.Items.Add("This"); ListBox1.Items.Add("That"); ListBox1.Items.Add("The other"); } } private void TextBox1_TextChanged(object sender, System.EventArgs e) { Response.Write("Text changed.<br>"); } private void ListBox1_SelectedIndexChanged(object sender, System.EventArgs e) { Response.Write("Item selected.<br>"); } private void Button1_Click(object sender, System.EventArgs e) { Response.Write("Page load.<br>"); }

When you run the preceding code, the page displays the event order, as shown in Figure 4-10. The Click event procedure is the last control event processed on a page.

figure 4-10 event order

Figure 4-10. Event order

Using the Button and LinkButton controls Click event procedure is straightforward. The ImageButton control provides an additional capability. The Click event argument for the ImageButton control includes the xy-coordinates for where the user clicked on the control. The image response depends on where it was clicked, as shown in Figure 4-11. Images that respond to clicks in this way are called image maps.

figure 4-11 imagebutton control

Figure 4-11. ImageButton control

The following code uses the ImageButton control s e.X and e.Y arguments to calculate which circle was clicked in Figure 4-11:

Visual Basic .NET

Private Sub ImageButton1_Click(ByVal sender As System.Object, _ ByVal e As System.Web.UI.ImageClickEventArgs) Handles ImageButton1.Click Dim xOffset, yOffset, X, Y, Radius As Single Dim strMessage As String ' Calculate the radius of the click from X, Y. xOffset = CSng(sender.width.value) / 2 yOffset = CSng(sender.height.value) / 2 X = System.Math.Abs(CSng(e.X) - xOffset) Y = System.Math.Abs(CSng(e.Y) - yOffset) Radius = System.Math.Sqrt((X ^ 2) + (Y ^ 2)) ' Set the message to display. Select Case CInt(Radius) Case 0 To 21 strMessage = "on center circle." Case 22 To 42 strMessage = "on second circle." Case 43 To 64 strMessage = "on third circle." Case 65 To 86 strMessage = "on fourth circle." Case Else strMessage = "outside of circle." End Select ' Display the message. Label1.Text = "You clicked " & strMessage End Sub

Visual C#

private void ImageButton1_Click(System.Object sender, System.Web.UI.ImageClickEventArgs e) { double xOffset, yOffset, X, Y, Radius; string strMessage; // Calculate the radius of the click from X, Y. xOffset = Convert.ToDouble(ImageButton1.Width.Value) / 2; yOffset = Convert.ToDouble(ImageButton1.Height.Value) / 2; X = Math.Abs(Convert.ToDouble(e.X) - xOffset); Y = Math.Abs(Convert.ToDouble(e.Y) - yOffset); Radius = Math.Sqrt(Math.Pow(X, 2) + Math.Pow(Y, 2)); if (Radius < 22) { strMessage = "on center circle."; } else if ((Radius >= 22) && (Radius <= 42)) { strMessage = "on second circle."; } else if ((Radius > 42) && (Radius <= 64)) { strMessage = "on third circle."; } else if ((Radius > 64) && (Radius <= 86)) { strMessage = "on fourth circle."; } else { strMessage = "outside of circle."; } // Display the message. Label1.Text = "You clicked " + strMessage; }

Getting and Setting Values

Use the RadioButton, RadioButtonList, CheckBox, or CheckBoxList controls to get Boolean value settings from the user. As with the ListBox and DropDownList controls, use the Collection Editor to add items to a RadioButtonList or a CheckBoxList control. Click the control s Items property to display the Collection Editor for that control.

Use the Checked property to get the setting from a CheckBox or a RadioButton control. For example, the following code displays whether or not the CheckBox1 control is selected:

Visual Basic .NET

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Response.Write("Checkbox1 is " & CheckBox1.Checked.ToString) End Sub

Visual C#

private void Button1_Click(object sender, System.EventArgs e) { Response.Write("Checkbox1 is " + CheckBox1.Checked.ToString()); }

When you first draw a RadioButton control on a Web form, it doesn t automatically interact with the other RadioButton controls on the form the way OptionButton controls do on a Windows form. To get the controls to interact, you need to set the GroupName property for each RadioButton. Figure 4-12 shows three RadioButton controls with the same GroupName. Because these RadioButton controls have the same GroupName, selecting one clears any other selected control.

figure 4-12 grouped radiobutton controls

Figure 4-12. Grouped RadioButton controls

To get or set the values from a CheckBoxList or RadioButtonList control, use a For Each loop to check each control in the list. The controls contained in a CheckBoxList control are not CheckBox controls, as you might expect. Instead, the CheckBoxList and RadioButtonList controls contain ListControls. To determine the setting of a ListControl control, use the Selected property, as shown in the following code:

Visual Basic .NET

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Dim lstItem As ListItem For Each lstItem In RadioButtonList1.Items If lstItem.Selected Then Response.Write(lstItem.Text & " is selected.<br>") End If Next End Sub

Visual C#

private void Button1_Click(object sender, System.EventArgs e) { foreach (ListItem lstItem in RadioButtonList1.Items) { if (lstItem.Selected) Response.Write(lstItem.Text +  " is selected.<br>"); } }

Displaying Graphics and Advertisements

There are many ways to display graphics on a Web form:

  • As a background

    Use the Background property of the Web form to display an image on the entire page. Use the BackImageUrl property of the Panel control to display a background image in one region of a page, rather than over the entire page.

  • As a foreground

    Use the Image control to display images in the foreground.

  • As a button

    Use the ImageButton control to display images that respond to user events. See the section Performing Commands, earlier in this lesson, for an example of responding to click events on an image.

  • As an ad

    Use the AdRotator control to display images from a list of ads. Ads displayed in the AdRotator control contain hyperlinks to the advertiser s Web site.

The Image control does not respond to user events, but it allows you to display graphics dynamically based on input from other controls. To display an image in an Image control at run time, use the ImageUrl property. For example, the following code displays a picture of Venice, Italy, when the user clicks a button:

Visual Basic .NET

Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click Image1.ImageUrl = "gondola.jpg" End Sub

Visual C#

private void Button1_Click(object sender, System.EventArgs e) { Image1.ImageUrl = "gondola.jpg"; }

A common use of graphics is for advertisements most Internet ads are stored as .gif files. Visual Studio includes the AdRotator control to handle the tasks associated with displaying these types of ads. The AdRotator control uses an XML file to schedule the ads that are displayed. The XML file stores the URL of the advertisement s image, the URL of the page to display if the user clicks the ad, the priority of the ad, and other properties of the ad. At run time, the AdRotator control selects one of the ads listed in its XML file and displays it on the page.

To use the AdRotator control, follow these steps:

  1. Draw an AdRotator control on a Web form.

  2. Add an XML file to the current project and open it.

  3. In the Properties window, select the TargetSchema property, and then select AdRotator Schedule File from the drop-down list of property settings. Visual Studio adds the following lines to the XML file:

    <Advertisements xmlns=  "http://schemas.microsoft.com/AspNet/AdRotator-Schedule-File"> </Advertisements>

  4. Add <Ad> tags to the <Advertisements> section of the XML file for each ad you want to display.

  5. Save the XML file, and switch back to the Web form in Design view.

  6. Select the AdRotator control, and set the AdvertisementsFile property to the XML file you just created.

Now edit the XML file to display the desired information. For example, the following XML file displays two different ads:

<?xml version="1.0" encoding="utf-8" ?> <Advertisements xmlns=  "http://schemas.microsoft.com/AspNet/AdRotator-Schedule-File"> <Ad> <ImageUrl>../ads/sponsorad.gif</ImageUrl> <NavigateUrl>/ads/sponsorad.htm</NavigateUrl> <AlternateText>Click here to visit our sponsor.</AlternateText> <Keyword></Keyword> <Impressions>1</Impressions> </Ad> <Ad> <ImageUrl>../ads/net.gif</ImageUrl> <NavigateUrl>//www.gotdotnet.com</NavigateUrl> <AlternateText> ASP.NET tutorials and more.</AlternateText> <Keyword>ASP</Keyword> <Keyword>.NET</Keyword> <Impressions>5</Impressions> </Ad> </Advertisements>

The tags in the AdRotator XML schema are defined in Table 4-5.

Table 4-5. The AdRotator XML Schema

Tag

Meaning

<Ad>

Begins an ad.

<ImageUrl>

The address of the ad to display.

<NavigateUrl>

The address to navigate to if the user clicks the ad.

<AlternateText>

The text to display in a ToolTip if the user pauses the mouse over the ad. Also, if the ad at the ImageUrl address can t be displayed, this text appears in its place.

<Keyword>

A category name to use for filtering the ads to display.

<Impressions>

A number representing the likelihood that an ad will be displayed. Ads with higher numbers are more likely to be displayed.

Grouping Controls

Place controls in a group when you want to manipulate a particular region of your Web form in code. For example, you might want to allow users to log on to a system from a region of a page and then hide or disable that region once they are logged on.

Use the Panel control to group controls on a Web form. Using the Panel control on a Web form is different from using the Panel control on a Windows form. For one thing, you can t draw controls on a Panel control. You must first draw your controls on the Web form, and then drag them onto the Panel control. For another thing, the Web Forms Panel control uses flow layout rather than grid layout. This means that you can t drag a control to an exact position on a panel.

NOTE
You don t have to place RadioButton controls in a panel to get them to work together. Instead, you enter a name in their GroupName property. See the section Getting and Setting Values, earlier in this lesson, for more information.

To position controls on a Panel control, follow these steps:

  1. Draw the controls on the Web form.

  2. Drag the controls onto the Panel control in the order in which you want them displayed. Visual Studio will place each control immediately after the next in sequence.

  3. Use carriage returns and spaces to place the controls where you want them to appear.

Figure 4-13 shows a group of controls that allow you to log on to a Web site. After the user logs on, the panel is hidden and a welcome message is displayed.

figure 4-13 positioning controls in a panel

Figure 4-13. Positioning controls in a panel

The following code hides the panel after the user is logged on:

Visual Basic .NET

Private Sub butOK_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butOK.Click ' If name/password match, hide logon panel and show message. If txtName.Text = "Guest" And txtPassword.Text = "Wombat" Then pnlLogon.Visible = False lblWelcome.Text = "Welcome " & txtName.Text Else txtPassword.Text = "" vldPassword.Validate() End If End Sub

Visual C#

private void butOK_Click(object sender, System.EventArgs e) { // If name/password match, hide the logon panel // and show message. if ((txtName.Text == "Guest") && (txtPassword.Text == "Wombat")) { pnlLogon.Visible = False; lblWelcome.Text = "Welcome " + txtName.Text; } else { txtPassword.Text = ""; vldPassword.Validate(); } }

Getting Dates

Use the Calendar control to get or display date information. The Calendar control provides properties to control the appearance of elements on the calendar, as shown in Figure 4-14.

figure 4-14 calendar control properties

Figure 4-14. Calendar control properties

To get or set dates selected on the Calendar control, use the SelectionChanged event procedure and the SelectedDate or SelectedDates properties. SelectionChanged is a postback event, so the following code displays the selected date or dates as soon as the selection changes:

Visual Basic .NET

Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load ' Display current date in the label to start. lblDate.Text = "Current date: " & Date.Now.Date End Sub Private Sub calSource_SelectionChanged(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles calSource.SelectionChanged If calSource.SelectedDates.Count = 1 Then ' If one date is selected, display it in a label. lblDate.Text = "Selected date: " & calSource.SelectedDate Else ' If multiple dates are selected, display them. lblDate.Text = "Selected dates: " & calSource.SelectedDates(0) & _  " to " & _ calSource.SelectedDates(calSource.SelectedDates.Count - 1) End If End Sub

Visual C#

private void Page_Load(object sender, System.EventArgs e) { // Display the current date. lblDate.Text = "Current date: " + calSource.TodaysDate; } private void calSource_SelectionChanged(object sender, System.EventArgs e) { // Display the current date. lblDate.Text = "Current date: " + calSource.TodaysDate; if (calSource.SelectedDates.Count == 1) // If one date is selected, display it. lblDate.Text = "Selected date: " + calSource.SelectedDate; else // If multiple dates are selected, display them. lblDate.Text = "Selected dates: " + calSource.SelectedDates[0] + " to " + calSource.SelectedDates [calSource.SelectedDates.Count - 1]; }

Getting Files from the Client

Use the File Field HTML control to upload files from the client to the server. The File Field HTML control is actually a Text Field HTML control and a Submit Button HTML control bound together. Clicking the Browse button runs a built-in script that displays the Windows Choose File dialog box on the client s computer, as shown in Figure 4-15.

figure 4-15 the windows choose file dialog box

Figure 4-15. The Windows Choose File dialog box

To receive the selected client file on the server, follow these steps:

  1. Draw a File Field HTML control on a Web form.

  2. Right-click the control, and select Run As Server Control from the shortcut menu.

  3. Right-click the Web form, and select View HTML Source. Visual Studio displays the HTML code for the Web form.

  4. Add an enctype attribute to the <form> tag in the Web form s HTML. The enctype attribute sets the MIME type of the form, and uploading a file requires both a MIME type of multipart/form-data and a form method of post, as shown here in boldface:

    <form action="webform1.aspx" method="post" enctype="multipart/form-data" runat="server" >

  5. Right-click the Web form, and select View Design from the shortcut menu. Visual Studio displays the Web Forms Designer.

  6. Add a Button control and a Click event procedure to the Web form to get and save the selected file. For example, the following event procedure saves the file to the server:

    Visual Basic .NET

    Private Sub butUpload_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butUpload.Click Dim strFilename As String Try ' Get the file name. strFilename = filUpload.PostedFile.FileName ' Exit if no file name was entered. If strFilename = "" Then Return ' If file has zero length (did not exist on client) If filUpload.PostedFile.ContentLength = 0 Then ' Display message. lblMsg.Text = "File not found on client or contains no data." ' Exit. Return End If ' Get the base name for the file (exclude path). strFilename = System.IO.Path.GetFileName(strFilename) ' Save uploaded file to server. filUpload.PostedFile.SaveAs(Request.MapPath("./uploadfiles") & _  "\" & strFilename) ' Add file to list of server files. lstServerFiles.Items.Add(strFilename) ' Select an item in the list. lstServerFiles.SelectedIndex = 0 Catch ex As System.UnauthorizedAccessException lblMsg.Text = "You must set the permissions on the server " & _  "to allow the ASPNET user to write to the destination folder." Catch ex As Exception lblMsg.Text = "An unexpected error occurred: " & ex.Message Finally End Try End Sub

    Visual C#

    private void butUpload_Click(object sender, System.EventArgs e) { string strFilename; try { // Get the file name. strFilename = filUpload.PostedFile.FileName; // Exit if no file name was entered. if (strFilename == "") return; // if file is zero length, it is empty or doesn't exist. if (filUpload.PostedFile.ContentLength == 0) { lblMsg.Text = "File was not found on client or file contains no data."; return; } // Get the base name for the file (exclude path). strFilename = System.IO.Path.GetFileName(strFilename); // Save uploaded file to server. filUpload.PostedFile.SaveAs(Request.MapPath("./uploadfiles") +  "\\" + strFilename); // Add file to list of server files. lstServerFiles.Items.Add(strFilename); // Select an item in the list. lstServerFiles.SelectedIndex = 0; } catch (System.UnauthorizedAccessException ex) { lblMsg.Text = "You must set the permissions on the server to allow the ASPNET user to write to the destination folder."; } catch (Exception ex) { lblMsg.Text = "An unexpected error occurred: "  + ex.Message; } finally {} }

The PostedFile method of the File Field HTML control represents the file being uploaded. You can use the FileName property and SaveAs method of the returned object to save the file on the server, as shown in the preceding code. The following code shows one way to retrieve the file from the server. In this case, the file is displayed in the browser.

Visual Basic .NET

Private Sub butView_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butView.Click Dim strFilename As String ' Get selected file name. strFilename = lstServerFiles.SelectedItem.ToString ' Display as Web page. Response.Redirect("./uploadfiles/" & "/" & strFilename) End Sub

Visual C#

private void butView_Click(object sender, System.EventArgs e) { // Get selected file name. string strFilename = lstServerFiles.SelectedItem.ToString(); // Display as web page. Request.MapPath(".\\uploadfiles\\") + strFilename); }



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net