Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 40 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
40
Dung lượng
1,27 MB
Nội dung
& objSender.SelectedItem.Value & "'" End Sub Notice how, in this case, we simply access the SelectedItem property of the list control, which returns a reference to the first item in the list that is selected Extracting Multiple Selected Values from List Controls Both of the lists in the previous example allow only a single selection to be made This is always the case with a RadioButtonList, but we can specify that a ListBox control will accept multiple selections by setting the SelectionMode property to the value ListSelectionMode.Multiple And of course, in a CheckBoxList we will usually allow multiple item selection, as this is generally the sole reason for using this type of control We extract multiple selected values from a list control using exactly the same technique as we did with the HtmlSelect control in the previous section We iterate through all the ListItem elements in the Items collection exposed by the list control, checking the Selected property of each one and extracting the Text and Value properties for those that are selected: Sub MyCode(objSender As Object, objArgs As EventArgs) Dim strResult As String strResult = "The following items were selected:" Dim objItem As ListItem For Each objItem in objSender.Items If objItem.Selected Then strResult += objItem.Text & " = " & objItem.Value & "" End If Next outMessage.InnerHtml = strResult End Sub Other ASP.NET Rich Controls To finish off this chapter, we will look briefly at three other controls that are provided with ASP.NET These are called rich controls because they create the entire HTML required to implement a complex task in one simple operation A typical example of this is the Calendar control, which can create a complete working calendar within a web page All you is add the control to your page and set a few properties The three controls we'll be covering here are: Control Description Displays an advertisement banner that changes on a predefined schedule Displays a calendar showing single months and allows selection of a date Displays the content of an XML document or the result of an XSL or XSLT transformation Using the Rich Controls The rich controls we are looking at in this section are very useful when you need to perform the specific tasks for which they are designed We don't have room to provide exhaustive coverage here, but by now you should be familiar with the way that server controls work, and you should have no problem getting to grips with these You can use the demonstration application we provide (open the Other Controls section of the left-hand menu) to see the output that they generate, and experiment with the various property settings The ASP:AdRotator Control The AdRotator control has been part of ASP almost since the beginning, and is a popular way to display advertisement banners on a quasi-random pre-defined schedule A new version is included as part of the default ASP.NET installation, and it has a couple of extra features Probably the most useful is the ability to filter the list of banners that will be displayed dynamically, so that you can, for example, display banners for products or organizations that are relevant to a specific page or user The filtering is carried out through the KeywordFilter property You can see that we have set this property in the following screenshot from our demonstration application: The code we used to insert the control into the page for this example is: Previous versions of the AdRotator control relied on a text file to specify the advertisements and the schedule for display of each one As the whole world is now going XML crazy, the new control follows the trend by using an XML file to define the schedules The file path is specified in the AdvertisementFile property, as shown in the sourcecode for the page above (you can't change this property in the demonstration page) The AdRotator Schedule File An example of the format of the XML schedule file is: ads/asptoday.gif http://www.asptoday.com/ ASPToday 20 Articles ads/wrox.gif http://www.wrox.com/ Wrox Press 20 Books more elements here The ImageUrl and NavigateUrl are self-explanatory The AlternateText is used as the HTML alt attribute of the element that the AdRotator control creates, and the Impressions value is used to control how often this banner will appear The total for this element in all the elements in the schedule file is calculated, and the ratio of impressions can then be calculated by the control and used to select the advertisement to display The Keyword element is used to allocate each advertisement to a 'category' with that name When you set the KeywordFilter property, only advertisements with the specified value for their Keyword element are included in the selection and display process The ASP:Calendar Control By far the most complex server control in ASP.NET is the Calendar control This creates a fully interactive 'one-month-at-a-time' calendar as an HTML table The next screenshot shows the default output from the Calendar control, and you can see that it really is a 'rich' control in that it saves an incredible amount of effort on behalf of the developer: The code we used to insert the control into the source of the page is: Notice that it automatically defaults to the current date if we don't specify a date If you scroll to the bottom of this page, you can see some of the properties that we can set to change the appearance These don't include the various calendarspecific style properties that are available, such as DayHeaderStyle, DayStyle, MonthStyle, and so on: The Calendar control also exposes a couple of events that we can use to detect when the user interacts with the control We can write an event handler for the SelectionChanged event, and obtain the date that the user selected by querying the SelectedDate property of the control within that event handler We can also create an event handler for the VisibleMonthChanged event In this case, the second parameter of the event handler is a MonthChangedEventHandler object, which exposes two properties named NewDate and PreviousDate that contain the original (before the month was changed) and current dates (the date after the month was changed) The ASP:Xml Control The final control we're looking at is the ASP:Xml server control This can be used to display the content of an XML document, or to perform a server-side transformation on the document using a suitable XSL or XSLT stylesheet Note that this control does not inherit from WebControl It inherits directly from Control, and so doesn't have all the displayoriented properties that the other Web Form controls Don't be confused into thinking that this control creates an IE 5-style element - it doesn't It is a server-side object that outputs XML or the result of an XSL or XSLT transformation to the client There are six properties available for the Xml control We specify the source document using one of the first three properties in the following table, and the stylesheet (if we're using one) in one of the next two properties shown in the table: Property Description A reference to an XmlDocument object that contains the XML document we want to display Document DocumentContent or transform We look at how we create and use the XmlDocument object in Chapter 11 A string containing the text of the XML document we want to display or transform A string that contains the physical or virtual path to the XML document we want to display DocumentSource or transform A reference to an XslTransform object that contains the XSL or XSLT stylesheet to use for Transform transforming the XML document before displaying it We look at how we create and use the XslTransform object in Chapter 11 A string that contains the physical or virtual path to the XSL or XSLT stylesheet we want to TransformSource use for the transformation A reference to an XsltArgumentList object that contains the arguments to be passed to TransformArgumentList the stylesheet In our demonstration page, we have set the DocumentSource property to books.xml The control loads this document from disk and displays it in the page Of course, the XML elements aren't visible, because the browser attempts to render the XML as though it were HTML and so only the text content of the elements is shown in the page If you view the source in your browser, however, you'll see the XML that the control sends to the client We have also included a hyperlink in the page so that you can open the XML document in a separate browser window and see it: The code we used to insert the control into the source of the page is: If you compare the original disk file with the output of the control, you will also see that the control has removed 'insignificant whitespace' from the result In other words, it strips out all the carriage returns, spaces, and tab characters Using an XSL Stylesheet We have also provided three simple XSL stylesheets that you can use to transform the XML document They transform the XML into HTML (because we are displaying it in the browser in our application) For example, the reportview.xsl stylesheet generates a sales report from the data in the XML document: Summary In this chapter, we have looked at the second major set of server controls that are provided as part of the default ASP.NET installation - the Web Form controls These are a mixture of simple controls that emulate the HTML controls we looked at in the previous chapter, and more complex controls that provide 'rich' output containing more than one HTML element The Web Form controls also have other advantages over the HTML controls They provide a consistent object model, using the same property name in all the controls for the same 'value' An example is the Text property, which sets the visible text within the control irrespective of which HTML element is output, and which HTML attribute carries the text content This makes working with them easier, and also simplifies the task of building tools or applications that will create a user interface automatically The Web Form controls we examined in this chapter fall into three groups: The basic controls, such as Image, Hyperlink, TextBox, and RadioButton The list controls, such as ListBox, DropDownList, and RadioButtonList The rich controls, such as AdRotator, Calendar, and Xml We showed you the common properties for each one, and demonstrated them through a sample application that we provide We also looked at how we react to events that these controls expose, and some of the other issues involved when we come to use them The topics we covered in this chapter were: The ASP.NET Web Form server controls in general The basic Web Form input and navigation server controls The Web Form server controls used for building lists The 'rich' Web Form controls that provide complex compound interface elements However, we didn't examine all the list controls in this chapter, as there are some very specialist ones such as Repeater, DataList, and DataGrid We look at these in the next chapter List Controls and Data Binding Most dynamic web sites, and just about every web-based application, will need to access a data source at some point ASP has long been capable of accessing various kinds of data store, such as relational databases, e-mail servers, XML documents, or text files and it's relatively simple to manipulate, format, and display data in a range of ways However, though it's simple to do, it always requires writing code - and that code can become quite extensive, making it difficult to manage and debug ASP.NET introduces some new ways to manage and present data of all kinds In later chapters we'll be looking at the whole concept of data management for both relational and XML data However, in this chapter we'll stick to looking at some of the new ways that we can display data in our web pages and applications This might seem to be an odd ordering of topics, but data presentation in ASP.NET is managed mainly through a series of new server controls that are specially designed to work with a whole range of types of data- not just relational or XML data This means that the techniques for working with these controls are akin to the techniques for creating ASP.NET pages that we've examined in previous chapters What's more, we don't need a deep understanding of where the data comes from, or how it is extracted from a data store, to be able to use the new data presentation controls The fundamentally disconnected design of the data management features within the NET Framework means that we can easily separate the business rules that create and expose data from the code that creates the display So, in this chapter, we'll deal with the way that the controls work, and how we use them In later chapters we'll be free to examine relational and XML data management techniques, without getting bogged down in presentation issues The topics we'll cover here are: What data binding actually is, and how it works How we can bind controls to single data values How we can bind list controls to sets of data values How we can change the appearance of data-bound controls How we can use data-bound controls to edit and update the source data However, data sources used for repeated-value binding often have more than one "field" (that is, more than one value in each row or "list item") Examples include the HashTable, which contains a Key and a Value, and the DataView or DataReader object where each item is itself a DataRow object In this case, we have to be able to specify which field or column (that is, which value from each row or list item) we want to bind to the control Many of the list controls are also capable of displaying or using more than one value for each item in the list For example, a element can use one value for the content of an element, and one value for that element's value attribute: Text1 Text2 Mapping Fields in the Data Source to Control Properties There are two ways that we can map (or connect) specific fields in each row of the data source to the properties or attributes of a control Which method we use depends on the type of control we are binding to: If the control supports templates, we can declaratively create a template that defines the content of each 'row' or item that the control will display If the control does not support templates, we can dynamically assign the fields in the data source to the attributes of the control by setting the properties of the control at runtime The controls in ASP.NET that support templates are Repeater, DataList, and DataGrid So, for one of these controls, we can declare a template within the control element and place our data binding instructions within it We reference the row or list item as a DataItem object within the control's Container, and specify the field or column that we want to connect to For example, when binding to a HashTable we specify either the Key property or the Value property: Key: or: Value: When binding to a Collection, DataView, or DataReader object, we specify the property, field, or column name itself: Value from DataView/DataReader: or: Value from Collection: So, for example, we could use a Repeater control to display the Key and Value in each row of a HashTable like this: = Then, in our Page_Load event handler, we simply assign the data source to the control and call its DataBind method: MyRepeater.DataSource = tabValues MyRepeater.DataBind() Mapping Fields Dynamically at Runtime For controls that don't support templates, we must set the properties (listed earlier) at runtime These properties specify the field from the data source that will provide the visible output for the control (the DataTextField property) and the field that will provide the non-displayed values for the control (the DataValueField property) So, using our previous example of a list populated from a HashTable, we could use one 'column' (probably the Key) as the value attribute of each element and the other 'column' (the Value) as the text of the element We declare the control like this: Then we set the properties of the control in the Page_Load event to display the appropriate fields from the data source: MySelectList.DataSource = tabValues MySelectList.DataValueField = "Key" MySelectList.DataTextField = "Value" MySelectList.DataBind() The DataGrid control is clever enough to be able to figure out fields in the data source automatically, and display all the values This works when the data source is an Array, a DataView, a DataSet or a DataReader, but not when the data source is a HashTable We'll look at the DataGrid control in detail towards the end of this chapter Evaluating Expressions with the Eval Method The data-binding statement block in a control that uses templates (such as the Repeater, DataList and DataGrid) can contain instances of only the following expression and derivatives of it In its simplest form, this expression is: A common derivative is the use of the Eval method of the DataBinder object to specify a value within a data source (where it contains more than one value per row), and optionally format the value for display In fact there are three ways that we can use the Eval method: When each row or list item in the data source contains more than one value (more than one column or field), for example a row from a DataView based on a database table, or a HashTable object When we want to use a different object than the one the control is bound to as the source of the value When we want to format the value for display, for example by taking a numeric value and formatting it as currency The first of these is just an extension of the syntax we used in the previous section, and adds nothing to the process other than a performance hit In general it should be avoided Here is an example, however, in which the value we want is in the column named BookTitle within a row in a DataView object: The DataBinder.Eval method uses a technique called late-bound reflection to evaluate the expression Therefore it carries a noticeable performance overhead compared to the standard data-binding syntax in which just the value name is specified Another important point is that we have to include a line-continuation character in Visual Basic when we use the Eval statement if we need to break the statement over more than one line This shouldn't really be necessary, but bear it in mind when you are reading published code listings in which the code could wrap to the next line The second way we can use the Eval method is when we want to bind to an object that is not defined in the DataSource for the control This allows us to reference specific values in that object, which are then used in every row that is displayed For example, if we have a DataView named objCityData that contains information about cities, we can specify the value of the CityName column in the fourth row (rows are indexed from zero) of the DataView with: However, the most common and useful application of the Eval method is to format values for display We'll look at this topic next Formatting Values and Expressions with the Eval Method The Eval method takes three parameters, the last of which is optional This third parameter, which we didn't use in the previous examples, is a "format string" that defines the format of the output For example, we can specify that the content of the PublicationDate field in our data source should be displayed in standard date format using: The result from this example is something like "10 March 2001" (it depends on the regional settings of the server) When we use the Eval method we can only have one value in each expression, so the first number in the curly braces (a placeholder for the variable containing the value to be formatted) must always be zero The character(s) after the colon (in this case "D") denote the format itself The common format strings we use with numeric values are: Format character Description Example (US English culture) C or c Currency format $1,234.60, ($28.15), D or d Decimal format 205, 17534, -65 E or e Scientific (exponential) format 3.46E+21, -1.2e+3, 3.003E-15 Format character Description Example (US English culture) F or f Fixed-point format 34.300, -0.230 G or g General format Depends on actual value N or n Number format 3,456.23, 12.65, -1.534 P or p Percent format 45.6%, -10% X or x Hexadecimal format &H5f76, 0x4528 (depends on actual value) The common format strings we use with dates are: Format character Description Example (US English culture) d Short date M/d/yyyy D Long date dddd, MMMM dd, yyyy f Full (long date and short time) dddd, MMMM dd, yyyy HH:mm aa F Full (long date and long time) dddd, MMMM dd, yyyy HH:mm:ss aa g General (short date and short time) M/d/yyyy HH:mm aa G General (short date and long time) M/d/yyyy HH:mm:ss aa M or m Month and day MMMM dd R or r RFC1123 format ddd, dd MMM yyyy HH:mm:ssGMT s ISO 8601 sortable using local time yyyy-MM-dd HH:mm:ss t Short time HH:mm aa T Long time HH:mm:ss aa u ISO 8601 sortable using universal time yyyy-MM-dd HH:mm:ss U Universal sortable date/time dddd, MMMM dd, yyyy HH:mm:ss aa Y or y Year and month MMMM, yyyy It's also possible to use the characters in the following table to create a "picture" for numeric values For example the format string "00#.##", when applied to the number 1.2345 would produce "001.23" If we want to specify positive, negative and zero formats, we separate each with semi-colons So given the format string "00#.##;(00#.##);[0]", we would get "(001.23)" for the number -1.2345 and "[0]" for zero The picture format characters for numbers are: Format character Description Displays a zero if there is no significant value- that is, it adds a zero in front of a number, or at the end of the number after the decimal point Digit placeholder, replaced only with significant digits Other occurrences of this symbol are ignored if # there is no significant digit Displays the decimal point character used by the current culture Separates number groups with the character used by the current culture, such as "1,000" in the US , English culture Can also be used to divide the value of a number, for example, the format string "0,," will display the number 100,000,000 as just 100 in the US English culture % E+0, E-0, e+0 or e-0 Displays the percent character used by the current culture Formats the output as scientific or exponential notation \ Displays the following character as a literal - it is not interpreted as a format character " or ' Any characters enclosed in single or double quotes are interpreted as a literal string { and } ; Double curly brackets are used to display a single literal curly brace For example "{{" displays "{" and "}}" displays "}" Separates the two or three sections for positive, negative, and zero values in the format string All other characters are copied directly to the output, so the format string "My value is: #.00" would, with the number 42, produce "My value is: 42.00" Remember that the DataBinder.Eval method carries a noticeable performance overhead compared to the standard data-binding syntax of specifying just the value name, and you should use it only when necessary In particular, avoid it when formatting of the value is not actually required You can often format values as you extract them from a database, or within the definition of the property or method that provides the bound values Simple Repeated-Value Data Binding Examples We've provided five example pages that are fundamentally similar, but demonstrate the different types of data source we can use with repeated-value data binding There are examples of binding to an ArrayList, a HashTable, a DataView, a DataSet and a DataReader We'll start with the ArrayList example, and then show you the particular differences between this and each of the other examples in turn Repeated-Value Binding to an ArrayList Object The simplest example of repeated-value data binding uses a one-dimensional ArrayList that is created and populated with values in the Page_Load event handler This example page, Simple Repeated-Value Data Binding (simple-repeated-binding.aspx) includes one of each of the eight list controls bound to our ArrayList: How It Works The HTML section of the page contains the definition of the eight list controls You can see that, with the exception of the Repeater and DataList controls, all we is declare the control itself: HTML <select> element: <ASP:DropDownList> control: <ASP:ListBox> control: <ASP:DataGrid> control: <ASP:Repeater> control: <ASP:DataList> control: <ASP:CheckBoxList> control: <ASP:RadioButtonList> control: However, the Repeater and DataList controls require that we specify the output we want for each repeated item, and so for these we've included an specification as well Whatever we put inside the is executed once for each repeated item In our code, we're just specifying the DataItem itself - the value of that item within the ArrayList The Page_Load Event Handler The remainder of the page is the event handler that runs when the page is loaded It simply creates a new ArrayList and fills it with five string values Then it sets the DataSource property of each of the eight list controls to this ArrayList and calls the DataBind method of the Page object to bind all the controls: Sub Page_Load() 'create an ArrayList of values to bind to Dim arrValues As New ArrayList(4) arrValues.Add("Microsoft") arrValues.Add("Sun") arrValues.Add("IBM") arrValues.Add("Compaq") arrValues.Add("Oracle") 'set the DataSource propert of the controls to the array MySelectList.DataSource = arrValues MyDropDown.DataSource = arrValues MyASPList.DataSource = arrValues MyDataGrid.DataSource = arrValues MyRepeater.DataSource = arrValues MyDataList.DataSource = arrValues MyCheckList.DataSource = arrValues MyRadioList.DataSource = arrValues 'bind all the controls on the page Page.DataBind() End Sub How the Controls Are Bound To understand what the controls are doing when data binding takes place, it's worth taking a look at the actual HTML that is created You can this by viewing the source of the page in your browser (if you're using Internet Explorer right-click the page and select View Source) The simple list controls (the HTML , ASP:DropDownList, and ASP:ListBox controls) are all persisted to the client as elements Each element within the list has the values from the ArrayList items as both the value attribute and the text of the element: Microsoft Sun IBM Compaq Oracle The DataList control creates an HTML and populates it with rows and cells containing the values from the ArrayList The DataGrid control does the same, but adds a row containing the column name (in this case Item) as well: Item Microsoft Sun IBM Compaq Oracle The CheckBoxList and RadioButtonList also both produce a table, but this time each cell contains either a checkbox control or a radio button control The CheckBoxList control simply uses the values from the ArrayList as the captions for each checkbox - it doesn't set the attribute of each one: Microsoft However, the RadioButtonList does set the value as well as the caption for each radio button, and all the radio buttons have the same name attribute (the name we gave to the control), so they operate as a radio button group: Microsoft Finally, the output from the Repeater control is just a list of the values with no formatting: Microsoft Sun IBM Compaq Oracle Repeated-Value Binding to a HashTable Object To demonstrate the differences in the way we handle other types of data source, the next example page binds the eight types of list control to a HashTable object rather than an ArrayList Run the example page, Repeated-Value Data Binding to a HashTable (hashtable-binding.aspx) to see the difference One thing you'll notice immediately is that two of each of the first three controls are included, and they contain different sets of values: How It Works In this case, the data source is not a simple array of values, but a Dictionary-style object known as a HashTable Each of the repeated items in the HashTable contains a Key and a Value So, in this case, we have to specify which of these we want to bind each control to In the case of the first three list controls (the HTML , ASP:DropDownList, and ASP:ListBox controls), we've bound one control to the Key of the HashTable and the other to the Value So, the HTML section of the page looks like this: HTML <select> elements: <ASP:DropDownList> controls: <ASP:ListBox> controls: <ASP:DataGrid> control: <ASP:Repeater> control: ...outMessage.InnerHtml = strResult End Sub Other ASP.NET Rich Controls To finish off this chapter, we will look briefly at three other controls that are provided with ASP.NET These are called rich controls... to be an odd ordering of topics, but data presentation in ASP.NET is managed mainly through a series of new server controls that are specially designed to work with a whole range of types of... in ASP.NET, we simply tell the controls or the page where to find the data It extracts the values and builds the page with this data in it We''ll see how next Displaying Data - ASP versus ASP.NET