1. Trang chủ
  2. » Công Nghệ Thông Tin

Professional ASP.NET 1.0 Special Edition- P11 pdf

40 260 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 40
Dung lượng 853,26 KB

Nội dung

=

<ASP:DataList> control: ''- value:

<ASP:CheckBoxList> control:

<ASP:RadioButtonList> control:

The declaration of the HTML , ASP:DropDownList, and ASP:ListBox controls at the top of the page, and the ASP:CheckBoxList and ASP:RadioButtonList controls at the bottom of the page, is no different to the previous example - we just define the control itself However, the definition of the other three list controls has to take into account the new structure of the data source Binding a DataGrid Control To a HashTable The DataGrid control cannot figure out by itself how to handle a HashTable, and needs us to provide some help As you'll see in more detail later in this chapter, we this by setting the AutoGenerateColumns property of the control to False, and then using a element and ASP:BoundColumn controls to specify where the values should come from The two columns are bound to the Key and Value fields in each item using the following syntax We also specify a DataFormatString for the Value column so that it is displayed in currency format: Binding a Repeater and a DataList Control To a HashTable The Repeater and the DataList controls contain an entry as in the previous example where we used an ArrayList However, now we can include two values in each template - the Key property and the Value property We refer to these as properties of the DataItem object We're adding some extra layout information in these two controls In the Repeater control we're adding the equals sign between the Key and the Value, and a line break after each Key/Value pair In the DataList control, we wrap the output for each Key in single quotes, adding the word "value:" and formatting the Value property in scientific notation using the format string "{0:E}": <ASP:Repeater> control: =

<ASP:DataList> control: ''- value:

The Page_Load Event Handler When the page loads, we first create the HashTable and fill in some values: Sub Page_Load() 'create a HashTable of values to bind to Dim tabValues As New HashTable(5) tabValues.Add("Microsoft", 49.56) tabValues.Add("Sun", 28.33) tabValues.Add("IBM", 55) tabValues.Add("Compaq", 20.74) tabValues.Add("Oracle", 41.1) Then we can set the DataSource property of each of the controls on the page In this case, we have to set at least the DataSource and DataTextField properties of the HTML , ASP:DropDownList, and ASP:ListBox controls so that they know which field in the data source contains the values to display In fact we've exploited this by having the first control in each pair display the Key values from the HashTable, and the second display the actual values of each item in the HashTable We can also provide different values for the value attribute of the control if requiredwe've done this for the second one of each control listed next: 'first displays the Keys in the HashTable MySelectList1.DataSource = tabValues MySelectList1.DataTextField = "Key" 'second one displays the Values in the HashTable 'and uses the Keys as the values MySelectList2.DataSource = tabValues MySelectList2.DataValueField = "Key" MySelectList2.DataTextField = "Value" 'same applies to ASP: controls, except here 'we can also specify the format of the Key MyDropDown1.DataSource = tabValues MyDropDown1.DataTextField = "Key" MyDropDown2.DataSource = tabValues MyDropDown2.DataValueField = "Key" MyDropDown2.DataTextField = "Value" MyDropDown2.DataTextFormatString = "{0:F}" MyASPList1.DataSource = tabValues MyASPList1.DataTextField = "Key" MyASPList2.DataSource = tabValues MyASPList2.DataValueField = "Key" MyASPList2.DataTextField = "Value" MyASPList2.DataTextFormatString = "{0:C}" If you look back at the earlier screenshot, you can also see the results of setting the DataTextFormatString property of the ASP:DropDownList and ASP:ListBox controls For example, in the last four lines of the preceding code we bound the second ASP:ListBox control to the HashTable so that the text of each element is automatically formatted as a currency value Binding the DataGrid, Repeater, and DataList controls is easy because we specified how the columns should be mapped to the data source in the control definitions We just need to set the DataSource property of each one: MyDataGrid.DataSource = tabValues MyRepeater.DataSource = tabValues MyDataList.DataSource = tabValues For the final two list controls, the CheckBoxList and RadioButtonList, we can specify both the DataValueField and the DataTextField properties This is like the simple list controls such as the list, and allows us to use different fields from the HashTable for the value attribute and the text for the control's caption: 'in the CheckboxList we'll display the Title and 'use the Value as the control value MyCheckList.DataSource = tabValues MyCheckList.DataValueField = "Value" MyCheckList.DataTextField = "Key" 'in the RadioList we'll display and format the 'Value and use the Key as the control value MyRadioList.DataSource = tabValues MyRadioList.DataValueField = "Key" MyRadioList.DataTextField = "Value" MyRadioList.DataTextFormatString = "Percentage rate {0:F}%" The final part of the code in the Page_Load event simply calls the DataBind method of the page to perform the data binding: Page.DataBind() 'bind all the controls on the page End Sub How the Controls Are Bound If you view the output that this page creates in the browser, you'll see that (unlike in the previous ArrayList example where the value and text were the same) the second of the two lists in each group has the Key from each item in the HashTable as the value attribute of the elements, and the Value from each item in the HashTable as the text of each element: 28.33 55 41.1 49.56 20.74 In the RadioButtonList, this technique also gives an output that specifies the Key from each item in the HashTable as the value attribute The Value of each item in the HashTable is formatted and used as the text caption of the checkbox or radio button: Percentage rate 49.56% Repeated-Value Binding to a DataView Object Our third example of data binding is to a DataView object For this example we're using a custom user control that returns a DataView object from a database We've provided the scripts and instructions for creating this database with the sample files, as well as a Microsoft Access database that you can use instead We're putting off discussion of data access techniques until later in the book- it's not a vital topic here as long as you appreciate that basically each of the objects provides us with a set of data rows (a rowset) to which we can bind our controls In the next chapter we'll discuss in detail how we can use these objects to extract data from a relational database The example page, Repeated-Value Data Binding to a DataView Object (dataview-binding.aspx) contains the same eight list controls as we've used in the previous two examples However, now we are displaying information drawn from our database of Wrox books: How It Works The HTML section of this page is basically the same as the first ArrayList example The difference is the definition of the Repeater and the DataList controls In each case, we need to specify the way we want to generate the content of the control from the values that are available in each "list item" (that is, each data row) within our source DataView The Repeater control generates no layout information by default, so we have to create a template using an element We specify a element to get each item on a separate line, because the Repeater does not provide any intrinsic formatting Inside the element we place the text, HTML, and definitions of the fields in the data source that we want to display We're displaying the contents of three columns from the DataView - the Title, ISBN, and PublicationDate We also format the PublicationDate column using the DataBinder.Eval method: ISBN:   Published: The DataList control creates an HTML table by default, so in this case we just need to specify the column and formatting information, along with any text and HTML we want to include in the table cells in each row: ISBN:   Published: As we saw earlier, the DataGrid control is primarily designed to work with objects that are returned as the result of a database query, such as a DataView object- and so it will figure out what the column names and content are from the data source object automatically Therefore, we don't need to provide column information, we only need to place the DataGrid control in the page: The Page_Load Event Handler In this example, we're using two separate custom user controls that return a database connection string and a DataView object populated with details about some Wrox books All the code in this page has to is call functions in the user controls to get back the DataView object: 'get connection string from \global\connect-strings.ascx user control Dim strConnect As String = ctlConnectStrings.OLEDBConnectionString 'create a SQL statement to select some rows from the database Dim strSelect As String 'create a new DataRow object instance in this table objDataRow = objTable.NewRow() 'and fill in the values objDataRow("ISBN") = "1861004478" objDataRow("Title") = "Professional Application Center 2000" objDataRow("PublicationDate") = "2001-03-01" objDataRow("ImageURL") = "appcenter.gif" objDataRow("Precis") = "This book takes you through etc." objTable.Rows.Add(objDataRow) 'repeat process for other rows 'assign the DataTable's DefaultView object to the Repeater control MyRepeater.DataSource = objTable.DefaultView MyRepeater.DataBind() 'and bind (display) the data End Sub In the penultimate line of code, we simply assign the DataView object that is returned from the DefaultView property of the table to the DataSource property of the Repeater control Then we execute the DataBind method of the control to display the contents of the DataView Loading Templates Dynamically at Run-time The templates we used in the previous example were hard-coded into the source of the page But what happens if we want to change the template we use at run-time? The next example page, Loading Templates Dynamically with a DataList Control (datalist-load-template.aspx) demonstrates how we can this by dynamically loading templates using code The page includes a drop-down list from which we can select a color scheme for the output, and it loads the appropriate set of header, footer, item, and alternating item templates from disk each time: How It Works The HTML section of the page defines a element containing the drop-down list that is used to select the color scheme we want By setting the AutoPostback property to True (as we described in Chapter 6) we avoid the need for a separate button, as the form will be posted to the server automatically whenever the selection in the list is changed The remainder of the HTML defines our DataList control with minimal formatting, and a Label control where we'll display the names of the template files currently in use: Select your Template:

The Dynamic Template Files Dynamically loaded templates must be disk files stored within the same application - that is within the same folder or a subfolder of the page that uses them We've provided four templates for each color scheme (one each for the header, item, alternating item, and footer), placed in a folder named templates below the folder that contains our example page These template files contain just the contents of each of the templates, and omit the enclosing element For example, this is the template for items when the "bright" color scheme is selected: * ISBN:   Published: The Page_Load Event Handler When the page loads, we create a DataReader object that will return some data rows from our sample database Then we can create the filenames of the four templates we want for the selected color scheme If this is the first time the page has been loaded (meaning it's not a postback, so no color scheme has been selected yet) we use the default templates: Sub Page_Load() 'create a suitable DataReader object here Dim strFileName As String If Page.IsPostBack Then strFileName = TemplateList.SelectedItem.Value & ".ascx" Else strFileName = "default.ascx" End If Dim strHeadFile As String = "templates/head-" & strFileName Dim strItemFile As String = "templates/item-" & strFileName Dim strAltIFile As String = "templates/alt-" & strFileName Dim strFootFile As String = "templates/foot-" & strFileName Now that we have the filenames, we can load the templates by calling the LoadTemplate method of the Page object The reference returned by this method is assigned to the appropriate property of the DataList control: MyDataList.HeaderTemplate = Page.LoadTemplate(strHeadFile) MyDataList.ItemTemplate = Page.LoadTemplate(strItemFile) MyDataList.AlternatingItemTemplate = Page.LoadTemplate(strAltIFile) MyDataList.FooterTemplate = Page.LoadTemplate(strFootFile) The final tasks are to display the names of the templates in our Label control, and then to bind the DataReader object containing our data rows to the DataList control: lblFileNames.Text = "Loaded Templates from Disk:" _ & strHeadFile & "" & strItemFile & "" _ & strAltIFile & "" & strFootFile & "" MyDataList.DataSource = objDataReader MyDataList.DataBind() End Sub Multiple Column Layouts with a DataList Control The DataList control we used in the previous example creates output that is, by default, an HTML table containing the items we bind it to One very useful aspect of this control is the ability to change the layout of the table content by specifying the number of columns to use, and the order in which the columns are filled from the data source (that is, from top to bottom or from left to right) The example page Using Multiple Display Columns with a DataList Control (columns-datalist-template.aspx) shows this technique in use It displays six book cover images in two columns of three when the page is opened However, we can use the controls in the page to change the number of columns and the layout direction, as shown in the following screenshot: How It Works The HTML section of this page contains a element with the five radio buttons that control how the DataList should lay out the content We use the AutoPostback feature (as in the previous example) so that any change to the current settings automatically posts the values to the server, which regenerates the page with the new layout: Number of Columns: One   Two   Three Layout Direction: Horizontally   Vertically

The DataList control lays out its content using an HTML If you include a definition of a and the corresponding and elements within a DataList control's template, the contents of this table are ignored by default To display the content for each data item in a nested table, you must set the ExtractTemplateRows attribute to True for the DataList control, and use the , , and server controls within the templates to create the nested table Next comes the definition of the DataList control We've specified three templates to control the appearance of the header, footer, and each item - in this case using an element in the to display the cover images: Some of the Latest Wrox Press Books For more information visit http://www.wrox.com The Page_Load Event Handler The layout styles for the DataList are set in the Page_Load event handler code We start by checking if this is a postback, or if it's the first time the page has been loaded If it's a postback, we will already have the data source (an ArrayList in this case) available, so we only need to check what values were selected in the radio buttons and set the appropriate values for the RepeatColumns and RepeatDirection properties of the DataGrid This automatically lays out the contents in the required way, without the need to rebind the data source: Sub Page_Load() If Page.IsPostBack Then 'set the number of columns to display If Cols1.Checked = True Then MyDataList.RepeatColumns = If Cols2.Checked = True Then MyDataList.RepeatColumns = If Cols3.Checked = True Then MyDataList.RepeatColumns = 'set the repeat direction of the items in the columns If Horiz.Checked = True Then MyDataList.RepeatDirection = RepeatDirection.Horizontal End If If Vert.Checked = True Then MyDataList.RepeatDirection = RepeatDirection.Vertical End If However, if this is the first time that the page has been loaded (that is, it's not a postback), we must create and populate the ArrayList and bind it to our DataList control We also have to set the default values for our radio buttons, and set appropriate initial values for the properties of our DataList control: Else 'create an ArrayList of values to bind to Dim arrValues As New ArrayList(6) arrValues.Add("appcenter.gif") arrValues.Add("aspplus.gif") arrValues.Add("aspxml.gif") arrValues.Add("components.gif") arrValues.Add("webmaster.gif") arrValues.Add("asp3.gif") 'bind the ArrayList to the DataList control MyDataList.DataSource = arrValues MyDataList.DataBind() 'set default columns and direction when page first loads Cols2.Checked = True MyDataList.RepeatColumns = Horiz.Checked = True MyDataList.RepeatDirection = RepeatDirection.Horizontal End If End Sub We only have to create the data source once- when the page is first loaded, and not every time the user changes the layout The values from the ArrayList are persisted through the ViewState of the page However, you should be aware of issues that can arise from this We'll look at the whole concept of managing the ViewState later in this chapter, when we examine how we can sort and filter the rows displayed in a list control Custom and Hidden Columns in a DataGrid Templates are immensely powerful when used with the Repeater, DataList, and DataGrid controls In fact when we come to use a DataGrid control, they become almost indispensable The DataGrid control is very clever It automatically figures out how many columns are needed to display the contents of a data source such as a DataView or DataReader object, and adds the column names to the header row This means that, unlike the Repeater and DataList controls, we aren't required to include templates that define the content In other words we can just use: MyDataGrid.DataSource = objDataView MyDataGrid.DataBind() But what happens if we don't want to display all of the columns in the data source, or if we want to add custom columns to the output? It would be a shame to have to abandon the DataGrid, with all the extra features it provides, and go back to using a DataList or Repeater control Specifying a Custom Column Layout Instead, we can use templates to specify the column layout of the DataGrid control We set the AutoGenerateColumns property to False, and then use a element to specify the columns to be displayed Within the element, we can place a series of ASP:BoundColumn controls that define the column properties: So, the code above specifies that our control should display only the ISBN and Title columns from our data source, and that the columns should have the names Book Code and Book Title in the header row of the final output rather than the column name Adding Unbound Columns We can also add extra columns that are not part of the original rowset by using an ASP:TemplateColumn control and an ItemTemplate element For example, the following definition of a DataGrid control includes a column with the heading Information In each row of this column is an (unbound) ASP:Button control with the caption More Info: Formatting the Column Contents We can also change the appearance of each of the custom columns, and format the values they contain The following code defines a DataGrid like that we described earlier, but now it has a column with the heading Released that displays the value of the PublicationDate column in the source dataset The value is formatted as a date using the format string "{0:D}", and right-aligned in the column on a yellow background: There is also a column with the heading Buy Now in bold text It has a silver background with the content aligned centrally in the column, and each row contains an unbound checkbox control You can see all of the effects we've just been describing, plus one or two more, by running the example page Specifying the Columns in a DataGrid Control (columns-datagrid.aspx): Clicking the More Info buttons produces some text at the foot of the page (it's displayed in a Label control) This text would probably be extracted from the same database table (or another table) However, we haven't implemented that in our example, as we're more interested in the way that the DataGrid control is used How It Works The first part of the HTML is the definition of the two radio buttons that control the display of the "Released" column As in previous examples, we use automatic postback to make it more intuitive to use: ... objTable.NewRow() ''and fill in the values objDataRow("ISBN") = "1861004478" objDataRow("Title") = "Professional Application Center 2000" objDataRow("PublicationDate") = "2001-03-01" objDataRow("ImageURL")

Ngày đăng: 03/07/2014, 07:20

TỪ KHÓA LIÊN QUAN