8.3. Adding Controls


Before proceeding, delete the line that tells the time from your aspx page, so that you can start the next part clean. In fact, that is the last time you'll mix HTML and code; from now on you'll add controls to the aspx page, and code in the code-behind (aspx.vb) page.

You can add server-side controls to a web form in three ways: by dragging controls from the Toolbox to the Design page, by writing HTML into the source page, or by programmatically adding them at runtime. For example, suppose you want to use buttons to let the user choose one of three shippers provided in the Northwind database. To do so, click on Design view, and drag a RadioButtonList control onto the form, as shown in Figure 8-10.

Figure 8-10. Drag a RadioButtonList onto the form


Once the RadioButtonList control is on your form, click its smart tag and choose Edit Items to add items to the list, as shown in Figure 8-11.

Figure 8-11. Edit items in RadioButtonList


The ListItem Collection Editor opens. Click the Add button to add a List Item. Type in Text (e.g., "Speedy Express") and for the first item set Selected to true (to select the first radio button in the list). Add entries for "United Package" and for "Federal Shipping," as shown in Figure 8-12.

When you click OK, the three buttons appear in the group. Click on the group and go to the Properties window. Name the group rblShipper (by setting the ID property) and examine the other properties you can set for the group. Pay particular attention

Figure 8-12. List Item Collection Editor


to the RepeatDirection control (shown in Figure 8-13) which allows you to have the buttons stacked vertically or laid out horizontally.

Figure 8-13. RepeatDirection property


Switch to Source mode and examine the HTML that has been generated for you by the Design editor:

     <asp:RadioButtonList  runat="server">         <asp:ListItem Selected="True">Speedy Express</asp:ListItem>         <asp:ListItem>United Package</asp:ListItem>         <asp:ListItem>Federal Shipping</asp:ListItem>     </asp:RadioButtonList></div> 

You could, of course, have hand-coded this, but the designer is easier and less prone to typos. Feel free, however, to add additional ListItem controls by hand if you prefer; the changes will be reflected back in the designer.

You can add controls to a page in one of two modes. The default mode is FlowLayout. With FlowLayout, the controls are added to the form from top to bottom, as in a standard html document. The alternative is GridLayout, in which the controls are arranged in the browser using absolute positioning (x and y coordinates).

To change from Flow to Grid or back, change the PageLayout property of the document in Visual Studio .NET. In this book, we will always use the Flow mode, as the Grid mode clutters the code with positioning information and has pretty much fallen out of favor with many developers.


Return to Design mode and click on the RadioButtonList. In the Properties window, set the BackColor to a pale blue and set the BorderColor to red, as shown in Figure 8-14.

Figure 8-14. Setting radio button controls


Notice that you can type in the hex code for the color you want, or you can simply drop down the color picker. You can even type the word Red into the Border color property, and the standard red color will be chosen. (If you want to see the border, change the BorderStyle from its default setting of none to something like Solid). Switch back to Source mode and notice that your HTML has been updated appropriately:

     <asp:RadioButtonList          runat="server"     BackColor="#C0FFFF"     BorderColor="Red"     BorderStyle="Solid"> 

8.3.1. Server Controls

Web forms offer two types of server-side controls. The first is server-side HTML controls. These are HTML controls that you tag with the attribute runat="Server".

The alternative to marking HTML controls as server-side controls is to use ASP.NET web controls, also called ASP controls. Web controls have been designed to augment and replace the standard HTML controls. Web controls provide a more consistent object model and more consistently named attributes. For example, with HTML controls, there are myriad different ways to handle input:

     <input type="radio">     <input type="checkbox">     <input type="button">     <input type="text">     <textarea> 

Each of these behaves differently and takes different attributes. The web controls try to normalize the set of controls, using attributes consistently throughout the ASP control object model. The web controls that correspond to the preceding HTML server-side controls are:

     <asp:RadioButton>     <asp:CheckBox>     <asp:Button>     <asp:TextBox rows="1">     <asp:TextBox rows="5"> 

The remainder of this book focuses on web controls.

8.3.2. Adding Controls and Events

Before proceeding, let's start a new application that will build on what you already have. To do so, create a new web application, and name this one NorthWindASP.

To copy the existing web site's files into your new web site, click on WebSite Copy Web Site. The Copy Web Site page will open. In the upper left is the Connect to: drop down with a blue button next to it. Click on the button to display the Open Web Site Dialog, as shown in Figure 8-15.

Figure 8-15. Opening the web site to copy from


Select the web site you want to copy from and click Open. Your dialog is now set up to transfer the files. Highlight all the files in the remote web site, and click the transfer arrow, as shown in Figure 8-16.

Figure 8-16. Copy all target web site files to new web site


You can now close the Copy Web page (big X in upper righthand corner). Delete the Default.aspx web page (right-click on it in Solution explorer and choose Delete) and set the Welcome.aspx page to be the start page for your application (right-click on it in Solution explorer and choose Select As Start Page). Your new web site should be a duplicate of your old. Run it to make sure all is working properly.

8.3.3. Adding the Shipper Page

By adding just a few more controls, you can create a complete form with which users can interact. You will do this by adding a more appropriate greeting ("Welcome to NorthWind"), a text box to accept the name of the user, two new buttons (Order and Cancel), and text that provides feedback to the user. Figure 8-17 shows the finished form.

Right-click on the application and choose Add New Item. From the Add New Item dialog click on web form and name the new web form Shipper.aspx, as shown in Figure 8-18.

You'll want to lay out your new controls in a table, and the easiest way to do so is to drag a table from the Toolbox into the Source view (within the <div> tags in the form). Once the table is in place, you can easily add rows by typing the open angle bracket within the table: IntelliSense springs into action to help you create an ASP:TableRow tag (and its closing tag), as shown in Figure 8-19.

Figure 8-17. The completed shipper form


Figure 8-18. Add new web page


Figure 8-19. Adding a table row


Within the first row you'll add a table cell. Again IntelliSense makes this very easy. After adding the cell, click space, and all the attributes for the cell are displayed. You'll want to set its ColumnSpan attribute to 2, as shown in Figure 8-20.

Within the TableCell declaration, you can then type the welcome statement:

     <asp:TableCell ColumnSpan="2">Welcome to NorthWind</asp:TableCell> 

Figure 8-20. Setting the ColumnSpan attribute


XHTML-compliant HTML requires that the attribute values be in double quotes. Visual Studio 2005 can help you with that. Open the menu item Tools Options, open the Text editor section, and then open the HTML section. Within HTML click on the Format choice, and check the box under Automatic formatting options that says Insert attribute value quotes when typing, as shown in Figure 8-21.


Figure 8-21. Setting automatic HTML formatting


Create a second row with two columns. The first column will contain a text prompt. Drag a text box into the second column from the Toolbox, as shown in Figure 8-22.

Figure 8-22. Dragging a TextBox into a table cell


Your next step is to create a third row with the RadioButtonList that you created earlier on the welcome page. First, create the row and two columns (the first with the prompt Shipper).

The second column will be for a new RadioButtonList, but you'll create it first, and then add it to the table once you have it set the way you want. Click on Design view, and drag a RadioButtonList onto your form, below the table. Note that it is marked Unbound. Rather than populating this list with hard-coded list items (as you did previously), you'll bind this list to data from the database.

To do so, click on the smart tag, and then click Choose Data Source, as shown in Figure 8-23.

Figure 8-23. Choose data source for RadioButtonList


In the Data Source Configuration Wizard, choose <New Data Source . . . >. When you do, the Wizard brings up the various types of data sources you might choose. Click on SQL Database, and the Wizard offers to name the new data source SqlDataSource1. Click OK. The Wizard now wants you to choose an existing connection or to make a new connection. Create a connection to the Northwind database, as shown in previous chapters, and click Next. You are offered the opportunity to save this connection. Save it as NorthWindConnectionString and click Next.

The next step in the Wizard is to pick the fields you want from the table you want. You'll pick ShipperID and CompanyName from the Shippers table, as shown in Figure 8-24.

Figure 8-24. Setting the select statement


Click Next and you have an opportunity to test your query, as shown in Figure 8-25.

Figure 8-25. Testing the query


Notice that the CompanyName field has the data you wish to display. You'll want the ShipperID in the Value field for the list item so you can uniquely identify the chosen shipper.

Click Finish and you are returned to the Data Source Configuration Wizard. Now you can indicate which field to display and which to set as the value field for the RadioButtonList, as shown in Figure 8-26.

Figure 8-26. Setting the Display and Value fields


Once the RadioButtonList and its associated SqlDataSource are configured, return to source view, and move them into the table cell you held ready for them.

     <asp:TableRow runat="server">         <asp:TableCell runat="server">Shipper: </asp:TableCell>         <asp:TableCell runat="server">                 <asp:RadioButtonList                 DataSource                 DataTextField="CompanyName"                 DataValueField="ShipperID"                  runat="server" />                 <asp:SqlDataSource                 ConnectionString="<%$ ConnectionStrings:NorthwindConnectionString %>"                  runat="server"                 SelectCommand="SELECT [ShipperID], [CompanyName] FROM [Shippers]" />         </asp:TableCell>     </asp:TableRow> 

Visual Studio 2005 will not create the self-closing tags for the controls, I've done so to save space and because I believe it makes the code easier to read.


Finally, add two more rows, one with two buttons, and one with a label that has no text:

     <asp:TableRow>         <asp:TableCell>             <asp:Button  runat="server" Text="Order"/>         </asp:TableCell>         <asp:TableCell>             <asp:Button  runat="server" Text="Cancel"/>         </asp:TableCell>     </asp:TableRow>     <asp:TableRow>         <asp:TableCell ColumnSpan="2">             <asp:Label  runat="server"></asp:Label>         </asp:TableCell>     </asp:TableRow> 

Set Shipper.aspx as the start page and run the application. It should look like Figure 8-27.

Figure 8-27. The completed shipper form


This form will not win any awards for design, but it illustrates a number of key points about web forms. When the user clicks on the Order button, you'll check that the user has filled in his or her name, and you'll also provide feedback on which shipper was chosen. Remember, at design time you can't know the name of the shipper (this is obtained from the database) so you'll have to ask the RadioButtonList for the chosen name (and ID).

To accomplish all of this, switch to Design mode and double-click on the Order button. Visual Studio will put you in the code-behind page, and will create an event handler for the button's Click event.

You add the event-handling code, setting the text of the label to pick up the text from the text box and the text and value from the RadioButtonList, as shown in Example 8-1.

Example 8-1. Order button Click event handler
 Protected Sub btnOrder_Click( _ ByVal sender As Object, _ ByVal e As System.EventArgs) Handles btnOrder.Click     lblMsg.Text = "Thank you " + TextBox1.Text.Trim( ) + ".  You chose " + _         RadioButtonList1.SelectedItem.Text.ToString( ) + " whose ID is " + _         RadioButtonList1.SelectedValue.ToString( ) End Sub 

Run the program, click on one of the radio buttons, fill in the text box, and click Order. The label is filled in, as shown in Figure 8-28.

Figure 8-28. Testing the Shipper page


Stop and rerun the program; notice that none of the radio buttons is selected. Binding the list did not specify which one is the default. There are a number of ways around this, but the simplest is to override the OnLoad event and select the first radio button.

Return to Shipper.aspx.vb and place the cursor within the class, but not within the existing Sub. Type Protected Overrides. You will see a scrolling list of all the overrideable methods, properties, etc., as shown in Figure 8-29.

Figure 8-29. Overriding OnLoad


Note that I do not use the proper capitalization, but once I pick a method, Visual Studio 2005 will fix the capitalization for me, capitalizing the P in protected and the O in overrides.


You can scroll to OnLoad or you can start typing OnLoad; when it is highlighted, press Tab. The stub for the overridden method is created. A single line of code is inserted for you. Add a second line of code so that the entire Sub looks like this:

     Protected Overrides Sub OnLoad(ByVal e As System.EventArgs)         MyBase.OnLoad(e)         RadioButtonList1.SelectedIndex = 0     End Sub 

The first line calls the base class (System.Web.UI.Page) OnLoad( ) method, so that the Page can do whatever it needs to do to load, and then it executes your additional line of code to select the first button in the RadioButtonList.

The problem with this solution is subtle. If you run the application, you'll see that the first button is selected, but if you choose the second (or third) button and press Order, you'll find that the first button is reset. You can't seem to choose any but the first selection. This is because each time the page is loaded, the OnLoad event fires, and in that event handler you are (re)setting the selected index.

You only want to set this button the first time the page is loaded, not when it is posted back to the browser as a result of the Order button being clicked.

To solve this, wrap the setting in an If statement that tests if the page has been posted back.

     If IsPostBack = False Then RadioButtonList1.SelectedIndex = 0 

If you put an if statement all on one line you do not need the end if statement.


When you run the page, the IsPostBack property is checked. The first time the page is posted, this value is False and the radio button is set. If you click on a radio button and then press Order, the page is sent to the server for processing (where the btnOrder_Click handler is run) and then the page is posted back to the user. This time the IsPostBack property is true, and thus the code within the If statement is not run, and the user's choice is preserved, as shown in Figure 8-30.

Figure 8-30. The user's choice is preserved on postback


The new page knows what button was clicked, even though the Web itself is stateless. This is accomplished, in this case, through view state , as described in the next section.



Programming Visual Basic 2005
Programming Visual Basic 2005
ISBN: 0596009496
EAN: 2147483647
Year: 2006
Pages: 162
Authors: Jesse Liberty

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