Tài liệu ASP.NET 1.1 Insider Solutions- P5 doc

50 325 0
Tài liệu ASP.NET 1.1 Insider Solutions- P5 doc

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

dropbox.CssClass = CssClass.ToString() textbox2.CssClass = CssClass.ToString() End If dropbox.Attributes.Add(“onclick”, “selectList(‘“ & sCID _ & “‘, ‘dropbox’, ‘textbox2’)”) textbox2.Attributes.Add(“onkeyup”, “scrollList(‘“ & sCID _ & “‘, ‘dropbox’, ‘textbox2’)”) dropbtn.Attributes.Add(“onclick”, “return openList(‘“ _ & sCID & “‘)”) dropbox.DataSource = DataSource dropbox.DataTextField = DataTextField dropbox.DataTextFormatString = DataTextFormatString dropbox.DataBind() Else pchStandard.Visible = True If CssClass <> “” Then listbox.CssClass = CssClass textbox.CssClass = CssClass End If listbox.Attributes.Add(“onclick”, “selectList(‘“ & sCID _ & “‘, ‘listbox’, ‘textbox’)”) textbox.Attributes.Add(“onkeyup”, “scrollList(‘“ & sCID _ & “‘, ‘listbox’, ‘textbox’)”) listbox.DataSource = DataSource listbox.DataTextField = DataTextField listbox.DataTextFormatString = DataTextFormatString listbox.DataBind() End If SetWidth() SetRows() End Sub Now you can apply any CSS classname that may have been specified for the CssClass property to both the list and text box. Then you add the attributes to the text box and list that attach the client-side script functions. You use the complete ID of this instance of the user control (which you generated earlier) and specify the appropriate text box and list control IDs. If you’re creat- ing a drop-down combo box, you also have to connect the openList function to the list control. Next, you set the data binding properties of the list within the user control to the values speci- fied for the matching properties of the user control and call the DataBind method. In fact, you could check whether the DataSource property has been set first, before setting the properties and 5 Creating Reusable Content 188 LISTING 5.26 Continued 08 0672326744 CH05 5/4/04 12:26 PM Page 188 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 189 Using the ComboBox Control calling DataBind . This would probably be marginally more efficient, although the DataBind method does nothing if the DatSource property is empty. Finally, you call the SetWidth and SetRows routines again to ensure that any conflicting CSS styles are removed from the constituent controls. And that’s it; the ComboBox control is complete and ready to go. You’ll use it in a couple simple sample pages next to demonstrate setting the prop- erties and using data binding. Using the ComboBox Control The first example of using the ComboBox control contains three instances and applies three differ- ent styles to them so that you can see the possibilities (see Figure 5.10). You can find this page in the samples that you can download for this book (see www.daveandal.net/books/6744/ ), or you can just run it online on our server (also see www.daveandal.net/books/6744/ ). There is a [view source] link at the bottom of the page that you can use to see the source code and the source of the .ascx user control. FIGURE 5.10 The ComboBox user control demonstration page in action. The page contains a Register directive for the ComboBox control: <%@Register TagPrefix=”ahh” TagName=”ComboBox” Src=”ascx\combo.ascx” %> As shown in Listing 5.27, three instances of the ComboBox control are then declared within the <form> section of the page. However, because the constituent controls reside within a <div> 08 0672326744 CH05 5/4/04 12:26 PM Page 189 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. element or a <table> element (depending on the mode specified), you have to use another <table> element to place a caption next to them. Listing 5.27 shows the attributes you specify for each one to apply the CSS style class (defined elsewhere in the page) and the other proper- ties you set declaratively. LISTING 5.27 The Declaration of the ComboBox Controls in the Sample Page <form runat=”server”> <hr /> <table border=”0”><tr><td align=”right” valign=”top”> Simple Combo List Box:</td><td> <ahh:ComboBox id=”cboTest1” IsDropDownCombo=”False” runat=”server” /> </td></tr></table> <hr /> <table border=”0”><tr><td align=”right” valign=”top”> Styled Drop-down Combo Box:</td><td> <ahh:ComboBox id=”cboTest2” CssClass=”bluegray” IsDropDownCombo=”True” runat=”server” /> </td></tr></table> <hr /> <table border=”0”><tr><td align=”right” valign=”top”> Wide and More Rows Drop-down<br />Combo Box with Larger Font:</td><td> <ahh:ComboBox id=”cboTest3” CssClass=”reverse” Width=”300” Rows=”10” IsDropDownCombo=”True” runat=”server” /> </td></tr></table> <hr /> <b>Select Combo Box and specify action to apply</b>:<p /> <asp:RadioButtonList id=”optCbo” RepeatLayout=”Flow” RepeatDirection=”Horizontal” RepeatColumns=”3” runat=”server” > <asp:ListItem Value=”cboTest1” Text=”Simple &nbsp;” /> <asp:ListItem Value=”cboTest2” Text=”Styled &nbsp;” /> <asp:ListItem Value=”cboTest3” Text=”Wide and More Rows” /> </asp:RadioButtonList> <p /> <asp:Button Text=”&nbsp; &nbsp;” OnClick=”ShowMembers” runat=”server” /> Display the syntax by calling the ShowMembers method <p /> . . other controls here to set properties . . <asp:Label id=”lblResult” EnableViewState=”False” runat=”server” /> </form> 5 Creating Reusable Content 190 08 0672326744 CH05 5/4/04 12:26 PM Page 190 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 191 Using the ComboBox Control The sample page also contains a RadioButtonList control that is used to specify which of the three ComboBox controls you want to apply the property settings to dynamically and a series of controls to specify the action to carry out on the selected ComboBox control. They are not all shown in Listing 5.27 to avoid unnecessary duplication. Notice that the Value properties of the items in the RadioButtonList control are the IDs of the three ComboBox controls. Populating the ComboBox Controls from an ArrayList Instance The Page_Load event handler is shown in Listing 5.28. If the current request is not a postback, you set the radio button to the first option and then create an ArrayList instance containing the values to be displayed in the ComboBox control list. By using data binding, you can apply this to all three of the ComboBox controls, just as you would any other list control—but with one excep- tion. The user control in this example automatically calls the DataBind method when it loads (after the current Page_Load event has occurred for the hosting page), so you don’t do it here. You can also take advantage of the DataTextFormatString property exposed by the ComboBox control to specify how the values are formatted in the third instance. This gives the effect you see in Figure 5.10 (for example, Animal ‘buffalo’ ). LISTING 5.28 The Page_Load Event Handler in the Sample Page Sub Page_Load() If Not Page.IsPostback Then ‘ executed when page is first loaded ‘ select first combobox in radiobutton list optCbo.SelectedIndex = 0 ‘ create ArrayList to populate comboboxes Dim aVals As New ArrayList() aVals.Add(“aardvark”) aVals.Add(“baboon”) aVals.Add(“buffalo”) aVals.Add(“cheetah”) aVals.Add(“frog”) aVals.Add(“giraffe”) aVals.Add(“lion”) aVals.Add(“lynx”) ‘ assign to DataSource of comboboxes cboTest1.DataSource = aVals cboTest2.DataSource = aVals cboTest3.DataSource = aVals ‘ set display format string for third combobox 08 0672326744 CH05 5/4/04 12:26 PM Page 191 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. cboTest3.DataTextFormatString = “Animal ‘{0}’” End If End Sub Displaying the Members of the ComboBox User Control When the user clicks the Show Members button, the routine named ShowMembers in the hosting page is executed. In it, you first have to get a reference to the ComboBox control currently selected in the RadioButtonList control. Then you call the ShowMembers method of this ComboBox control to get back a string, and you display that in a Label control in the page (see Listing 5.29). To see the result of this, refer to Figure 5.9. LISTING 5.29 Calling the ShowMembers Method Sub ShowMembers(oSender As Object, oArgs As EventArgs) ‘ get a reference to the selected comboxbox control Dim oCtrl As Object = Page.FindControl(optCbo.SelectedValue) ‘ call ShowMembers method of combobox control lblResult.Text = oCtrl.ShowMembers() End Sub Displaying Details of the Selected Item The sample page contains a button that displays details of the item currently selected in the ComboBox control. Figure 5.11 shows the output that this generates in the page, and you can see the values for the SelectedIndex , SelectedValue , and SelectedItem properties, plus the items in the list, as obtained by iterating through the Items collection. 5 Creating Reusable Content 192 LISTING 5.28 Continued FIGURE 5.11 The output of the ShowMembers method of the ComboBox control, as displayed in a Web page. 08 0672326744 CH05 5/4/04 12:26 PM Page 192 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 193 Using the ComboBox Control Listing 5.30 shows the code that executes when this button in the hosting page is clicked. After the code gets a reference to the currently selected ComboBox control, a StringBuilder instance is used to create the string that is displayed in a Label control. Again, the process of extracting the values from the ComboBox control is exactly the same as you would use with any other Web Forms list control. LISTING 5.30 The ShowSelected Routine That Calls the ShowMembers Method Sub ShowSelected(oSender As Object, oArgs As EventArgs) ‘ get a reference to the selected comboxbox control Dim oCtrl As Object = Page.FindControl(optCbo.SelectedValue) ‘ use a StringBuilder to hold string for display Dim sResult As New StringBuilder(“<b>Property Values:</b><br />”) ‘ collect details of current selection from combobox sResult.Append(“SelectedIndex: “ & oCtrl.SelectedIndex & “<br />”) sResult.Append(“SelectedValue: “ & oCtrl.SelectedValue & “<br />”) sResult.Append(“SelectedItem.Text: “ & oCtrl.SelectedItem.Text & “<p />”) ‘ collect all items in the combobox list sResult.Append(“<b>ListItems Collection:</b><br />”) For Each iItem as ListItem In oCtrl.Items sResult.Append(iItem.Text & “<br />”) Next ‘ display results in the page lblResult.Text = sResult.ToString() End Sub Setting the Properties of the ComboBox User Control The remaining buttons in the sample page set various properties of the selected ComboBox control, including SelectedIndex , SelectedValue , Width , and Rows . They validate the values first to make sure they are of the correct data types and within range. Then, after obtaining a reference to the current ComboBox control, as in the previous examples, they apply the property setting(s) to it. This chapter doesn’t list all the code for these routines because it is extremely repetitive, but you can see it by using the [view source] link at the bottom of the page at www.daveandal.net/books/6744/ . 08 0672326744 CH05 5/4/04 12:26 PM Page 193 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. Populating the ComboBox Control The sample page described in this section ( populating.aspx ) demonstrates different ways of populating the ComboBox user control. As in the previous example, it registers the control with a Register directive and then declares three instances of it. This time, they are all of the default style. However, the lists are filled using three different techniques this time, as you can see in Figure 5.12. 5 Creating Reusable Content 194 FIGURE 5.12 Filling the ComboBox control list, using different data sources and data binding. The first list is filled using the same ArrayList instance as in the previous example. The second is filled from the Northwind sample database that is supplied with SQL Server, using the values from the ProductName column of the Products table. The third ComboBox control is filled by creat- ing new ListItem instances in code and adding them to the ComboBox control’s Items collection (the ListItemCollection instance exposed by the Items property). This section of code also demonstrates how you can access a specific item in the list and read or change its value. All this is done within the Page_Load event handler for the sample page, with the excep- tion of a separate routine that creates a DataReader instance for the table in the Northwind database. Listing 5.31 shows the complete code for this sample page. LISTING 5.31 Code That Demonstrates Techniques for Populating the ComboBox Control Sub Page_Load() If Not Page.IsPostback Then ‘ populate combobox controls Editing the Connection String You must edit the connection string in the web.config file to point to your database server, and you must specify the correct user- name and password if you run the examples on your own server. 08 0672326744 CH05 5/4/04 12:26 PM Page 194 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 195 Populating the ComboBox Control ‘ databind ArrayList to first one Dim aVals As New ArrayList() aVals.Add(“aardvark”) aVals.Add(“baboon”) aVals.Add(“buffalo”) aVals.Add(“cheetah”) aVals.Add(“frog”) aVals.Add(“giraffe”) aVals.Add(“lion”) aVals.Add(“lynx”) cboTest1.DataSource = aVals ‘ databind second combobox to a DataReader cboTest2.DataSource = GetDataReader() cboTest2.DataTextField = “ProductName” ‘ insert values directly into list for third combobox Dim oList As ListItemCollection = cboTest3.Items For iLoop As Integer = 1 To 9 oList.Add(New ListItem(“Item: “ & iLoop.ToString())) Next oList.Insert(3, New ListItem(“Inserted: 3a”)) End If End Sub Function GetDataReader() As OleDbDataReader ‘ get DataReader for rows from Northwind Products table Dim sConnect As String _ = ConfigurationSettings.AppSettings(“NorthwindOleDbConnectString”) Dim sSelect As String _ = “SELECT ProductName FROM Products WHERE ProductName LIKE ‘c%’” Dim oConnect As New OleDbConnection(sConnect) Try oConnect.Open() Dim oCommand As New OleDbCommand(sSelect, oConnect) Return oCommand.ExecuteReader(CommandBehavior.CloseConnection) Catch oErr As Exception LISTING 5.31 Continued 08 0672326744 CH05 5/4/04 12:26 PM Page 195 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. ‘ be sure to close connection if error occurs If oConnect.State <> ConnectionState.Closed Then oConnect.Close() End If ‘ display error message in page lblErr.Text = oErr.Message End Try End Function Summary This chapter begins by looking at the techniques that are available in ASP.NET for creating reusable content and for reducing the amount of repetitive work you need to do when building Web sites and Web applications. While the server-side include approach is still valid, there are better ways. User controls and custom server controls both offer advantages, and they provide a natural approach that integrates well with ASP.NET in both style and effectiveness. Other techniques briefly discussed in this chapter are using master pages and templates and wrapping existing COM/COM+ components for use in ASP.NET. Chapter 9, “Page Templates” looks in more depth at the first of these options, but this book does not pursue the COM/COM+ wrapper technique any further. The second part of this chapter walks through the design and construction of a nontrivial user control that implements a feature that is missing from the standard range of browser-based control elements—a dual-mode combo box. You saw how it uses constituent controls, how to expose properties and methods, and how to use code within the control to manage its behavior and appearance. Finally, to complete the chapter, you saw how you can use the new ComboBox control in ASP.NET pages. However, this chapter does not address a few issues. One is the way that the client-side script within the control works; we’ll come back to this issue in Chapter 6. Another is the general compatibility of the control in different browsers. As you’ve seen in this chapter, the sample ComboBox control works fine in Internet Explorer 5.0, and it also works well in the latest versions of Opera. However, there are issues in other browsers, especially older ones. In subse- quent chapters, you’ll see how you must understand the issues, how you can address them, and how you can build controls that adapt to suit a wider range of browser types. 5 Creating Reusable Content 196 LISTING 5.31 Continued 08 0672326744 CH05 5/4/04 12:26 PM Page 196 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 6 Client-Side Script Integration A SP.NET provides plenty of clever server- side controls that ultimately generate HTML elements in the browser. However, with the notable exception of the validation controls and one or two other features, that’s really all they do. In fact, when they start to build Web applications, most developers who are used to building Windows applications find that the interface features Web developers have become accustomed to using are quite poor. We can’t do much about the actual client- side HTML elements and controls that are available because that’s the whole nature of the Web. Content is supposed to be univer- sally supported in all browsers, and browsers are supposed to follow accepted standards. Therefore, if your application needs some fancy new kind of multistate psychedelic flashing button, you’re going to have to find a way to build it yourself. And depend- ing on how you implement it, you might then have to find a way to persuade all the people who use your site to download this great new control and install it on their machine. IN THIS CHAPTER Client-Side Interaction on the Web 198 Useful Client-Side Scripting Techniques 207 Summary 240 09 0672326744 CH06 5/4/04 12:24 PM Page 197 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. [...]... selectList Function to Work in Internet Explorer 4.x function selectList(sCtrlID, sListID, sTextID) { var list; var text; if (document.all) { list = document.all[sCtrlID + sListID]; text = document.all[sCtrlID + sTextID]; } else { list = document.getElementById(sCtrlID + sListID); text = document.getElementById(sCtrlID + sTextID); } text.value = list.options[list.selectedIndex].text; if (sListID == ‘dropbox’)... openList(sCtrlID) { var list = document.getElementById(sCtrlID + ‘dropbox’); var btnimg = document.getElementById(sCtrlID + ‘dropbtn’); if(list.style.display == ‘none’) { Client-Side Interaction on the Web LISTING 6.3 Continued list.style.display = ‘block’; btnimg.src = document.getElementById(sCtrlID + ‘imageup’).src; } else { list.style.display = ‘none’; btnimg.src = document.getElementById(sCtrlID... navigator.appVersion properties as well 201 202 6 Client-Side Script Integration LISTING 6.1 Detecting the Client’s Feature Support in Script Code if (document.getElementById) { code for CSS2-compliant browsers here } else if (document.all) { code for IE 4.x here } else if (document.layers) { code for Netscape Navigator 4.x here } else { code for older browsers here } However, as discussed earlier, the number... controls you want to manipulate by using the getElementById function that is exposed by the document object LISTING 6.3 The Client-Side Script for the ComboBox User Control function selectList(sCtrlID, sListID, sTextID) { var list = document.getElementById(sCtrlID + sListID); var text = document.getElementById(sCtrlID + sTextID); text.value = list.options[list.selectedIndex].text;... elements in a page by exposing them from the document object as a collection called all It also allowed selection of a set of elements by type, via the use of the getElementsByTagname method While CSS2 provides the same getElementsByTagname method, it replaces the document.all collection with two methods named getElementById and getElementByName Because ASP.NET sets the id and name attributes of an... Description document.all collection Supported by Internet Explorer 4.0 and above document.layers collection Supported by Netscape Navigator 4.x only getElementById method Supported by CSS2-compliant browsers By using the features described in Table 6.1, Using the ASP NET you can write code such as that shown in BrowserCapabilities Object Listing 6.1 to execute different sections of You can use the ASP.NET. .. = ‘block’; btnimg.src = document.getElementById(sCtrlID + ‘imageup’).src; } else { list.style.display = ‘none’; btnimg.src = document.getElementById(sCtrlID + ‘imagedown’).src; } Useful Client-Side Scripting Techniques The following sections demonstrate some useful client-side scripting techniques These techniques are some of the several that regularly crop up as questions on ASP.NET mailing lists and... document.getElementById(sCtrlID + sTextID); text.value = list.options[list.selectedIndex].text; if (sListID == ‘dropbox’) openList(sCtrlID); } function scrollList(sCtrlID, sListID, sTextID) { var list = document.getElementById(sCtrlID + sListID); var text = document.getElementById(sCtrlID + sTextID); var search = new String(text.value).toLowerCase(); list.selectedIndex = -1; var items = list.options; var option = new String();... issues that affect you when you create ASP.NET pages, as well as when you create reusable content such as user controls and server controls This is by no means a reference work on client-side scripting, but it reinforces some of the basic techniques and demonstrates useful ways that even very simple script can solve common issues you come up against when building ASP.NET Web applications Client-Side... this control (absolute positioning) are Internet Explorer 4.x and Netscape 4.x Because the Accessing the document.all Collection number of hits likely to be encountered from and the getElementID Method in these two browsers is negligible, it doesn’t JavaScript seem worth supporting them Remember that document.all is a collection However, extending support to Internet (array) of elements, so in JavaScript, . Content 18 8 LISTING 5.26 Continued 08 0672326744 CH05 5/4/04 12 :26 PM Page 18 8 Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark. 18 9. browser types. 5 Creating Reusable Content 19 6 LISTING 5. 31 Continued 08 0672326744 CH05 5/4/04 12 :26 PM Page 19 6 Please purchase PDF Split-Merge on www.verypdf.com

Ngày đăng: 24/12/2013, 04:16

Tài liệu cùng người dùng

Tài liệu liên quan