Manipulating data in asp.net 2.0 13: Using Templatefield_ self-study process in DetailsView controls

Source: Internet
Author: User
Tags bind eval html tags

Introduction

TemplateField provides a highly complex approach to data rendering, compared to BoundField, CheckBoxField, HyperLinkField, and other data field controls, which are also available in database fields controls. In the previous section, we focused primarily on using TemplateField in the GridView to achieve:

• Display multiple data fields in a column. For example, FirstName and LastName fields are combined to appear in a GridView column.

• Use interactive Web controls to present data. We saw how to use a Calendar control to display the value of a hireddate.

• Displays status information based on the potential data. Although the Employees table does not contain a data column about how long employees have worked in the company, we can still implement such functionality in the GridView using the TemplateField and formatting methods, as we did in the previous section.

As in the GridView, the DetailsView control can use the same TemplateField. In this tutorial, we will use a DetailsView that contains two TemplateField to display product information one at a time. The first TemplateField consolidates data such as UnitPrice, UnitsInStock, and UnitsOnOrder and is displayed on a DetailsView line. The first TemplateField will display the discontinued data, but the formatting method will be used to show "YES" when there is a discount, otherwise the "NO" is displayed.

Figure I: Using two template columns to customize the display

All right, let's get started!

The first step: binding Data to DetailsView

As discussed in the previous section, the easiest way to use TemplateField is to create a DetailsView control that contains only BoundField. Then add a new TemplateField or convert some BoundField to TemplateField. Therefore, we first add a DetailsView control to the page through the designer, and bind a ObjectDataSource that returns the product list to it. These actions will create a Detailsview,boundfield with BoundField and CheckBoxField for a non boolean value, CheckBoxField of course it is for a Boolean value (for example, "whether discount").

Open the Detailsviewtemplatefield.aspx page and drag a DetailsView from the toolbox to the designer. Select and add a new ObjectDataSource control that invokes the GetProducts () method of the Productsbll class from the DetailsView smart Tag (smart tag).

Figure II: Adding a new ObjectDataSource control that calls the GetProducts () method

In this report, delete the BoundField such as ProductID, SupplierID, CategoryID, and ReorderLevel. Then, adjust the order of the remaining BoundField to keep CategoryName and suppliername behind ProductName. Then set the HeaderText and formatting properties of each BoundField, do not be nervous, casually fill, as long as you feel cool on the line. As in the GridView, you can either use the Field dialog box or directly modify the declaration code (Declarative Syntax. Translator's note: What should literal translation be? Declaration syntax? Anyway, it's just the stuff in the HTML view to edit these bound columns. Finally, empty the height and width properties of the DetailsView so that it automatically expands according to the data that you want to display, and then select the Enable paging (enabled paging) check box on the smart tag.

After you make these changes, the declaration markup for your DetailsView control should be as follows:

<asp:detailsview id= "DetailsView1" runat= "Server" autogeneraterows= "False" datakeynames= "ProductID" DataSourceID = "ObjectDataSource1" allowpaging= "True" enableviewstate= "False" > <Fields> <asp:boundfield datafield= " ProductName "headertext=" Product "sortexpression=" ProductName "/> <asp:boundfield datafield=" CategoryName "Hea dertext= ' Category ' readonly= ' True ' sortexpression= ' CategoryName '/> <asp:boundfield ' datafield= ' SupplierName ' H eadertext= "Supplier" readonly= "True" sortexpression= "SupplierName"/> <asp:boundfield "datafield=" QuantityPerUnit "headertext=" Qty/unit "sortexpression=" QuantityPerUnit "/> <asp:boundfield DataField=" UnitPrice "headertext=" Price "sortexpression=" UnitPrice "/> <asp:boundfield datafield=" UnitsInStock "HeaderT Ext= "Units in the sortexpression=" UnitsInStock "/> <asp:boundfield datafield=" UnitsOnOrder "HeaderText=" unit s on order "sortexpression=" UnitsOnOrder "/> <asp:cHeckboxfield datafield= "discontinued" headertext= "discontinued" sortexpression= "discontinued"/> </Fields> </asp:DetailsView>

Again, we should take some time to look at the effect in the browser! Now you can see a separate product (Chai) that includes a number of rows showing its properties: Name, category, vendor, inventory, order quantity, and its discount status.

Figure three: Use a set of bound columns to display product details

Step two: Combine unit price, inventory and order quantity in one column

DetailsView has one column for UnitPrice, UnitsInStock and UnitsOnOrder. By TemplateField You can combine these 3 data into one line, you can add a new TemplateField, or you can UnitPrice, UnitsInStock or UnitsOnOrder any one of the BoundField to convert directly to TemplateField. Although I personally still like to convert the existing BoundField into TemplateField this way, but here we still contact to add a new TemplateField bar.

Click Edit Fields in the pop-up menu of the DetailsView smart tag. In the Pop-up Field dialog box, add a new TemplateField and set its HeaderText property to "Price and Inventory", and then move the new TemplateField to the top of the UnitPrice.

Figure Four: Add a template column to the DetailsView control

Since the newly added TemplateField will display data in BoundField such as UnitPrice, UnitsInStock, and UnitsOnOrder, let's delete these BoundField first.

The final task of this step is to define the TemplateField ItemTemplate of "Price and Inventory", which you can do by manually writing declarative code through the DetailsView template editing interface in the designer. Just like the GridView, by clicking Edit Templates in the pop-up menu of the smart tag, you can use the template editing interface. Here you can select the template you want to edit in the dropdown box and add any Web controls you like from the Toolbox.

In this tutorial, you first add a label to the ItemTemplate of the "Price and Inventory" template column. Then, on the label control's Smart label, tap Edit Data binding (edit DataBindings) and bind its Text property to the UnitPrice field.

Figure Five: Bind the label's Text property to the UnitPrice field

The unit price format is formatted as currency, and after doing so, only the unit price of the selected product is displayed on the label on the "Inventory" template column. Figure VI shows us the results we have done so far.

Figure VI: the "unit Price and Total" template column shows the unit price

Note that the unit price of the product is not formatted as currency now. If it is a BoundField, the format can be implemented by setting the HTMLEncode property to false and setting the DataFormatString property to "{0:formatspecifier}". However, in TemplateField, any formatting instructions must be specified in the data-binding syntax or by using a formatting method that is written somewhere in the application (for example, in the back code class of a ASP.net page).

To specify the format of the label's data-binding code, click Edit Data Binding (editor DataBindings) in the label's smart tag. Then enter the format description or select a predefined format string in the Format Drop-down box in the pop-up Data-binding dialog box. As with the dataformatstring attribute of BoundField, formatting is specified using {0:formatspecifier}. In order for the UnitPrice field to use currency format, we can select an appropriate value in that Drop-down box, or enter "{0:C}" directly.

Figure VII: Format the unit price in currency form

To illustrate, the format description is the second parameter of the bind or eval method. This setting that you just added through the designer is represented by the following markup language: <asp:label id= "Label1" runat= "text=" <%# Eval ("UnitPrice", "{0:c}")%> ' > </asp:Label> Add the remaining data fields to the TemplateField

Now, we've shown and formatted the UnitPrice field in the "Price and Inventory" template column, but I also need to show UnitsInStock and UnitsOnOrder. Let's show them in parentheses below the price line! In the designer's template editor, these markup languages for display can be simply typed with the keyboard, but you need to first position the cursor somewhere in the template. Alternatively, you can enter directly into the declaration code.

Static markup languages, label controls, and data-binding code are added, so the price and Inventory template columns can display unit prices and total information as follows:

Unit Price (in stock/on Orders: Stock/Order quantity)

After doing this, your DetailsView declaration tag code should look like this:

<asp:detailsview id= "DetailsView1" runat= "Server" autogeneraterows= "False" datakeynames= "ProductID" DataSourceID = "ObjectDataSource1" allowpaging= "True" enableviewstate= "False" > <Fields> <asp:boundfield datafield= " ProductName "headertext=" Product "sortexpression=" ProductName "/> <asp:boundfield datafield=" CategoryName "Hea
   dertext= "Category" readonly= "True" sortexpression= "CategoryName"/> <asp:boundfield "datafield=" headertext= "Supplier" readonly= "True" sortexpression= "SupplierName"/> <asp:boundfield "datafield=" QuantityPer Unit "headertext=" Qty/unit "sortexpression=" QuantityPerUnit "/> <asp:templatefield HeaderText=" Price and Invent  Ory "> <ItemTemplate> <asp:label id=" Label1 "runat=" server "text= ' <%#" Eval ("UnitPrice", "{0:C}") %> ' ></asp:Label> <br/> <strong> (in stock/on order: </strong> <asp:la
     Bel id= "Label2" runat= "Server"Text= ' <%# Eval ("UnitsInStock")%> ' ></asp:Label> <strong>/</strong> <asp:label id= ' La Bel3 "runat=" server "text= ' <%# Eval (" UnitsOnOrder ")%> ' > </asp:Label><strong>) </strong&gt
   ; </ItemTemplate> </asp:TemplateField> <asp:checkboxfield datafield= "discontinued" headertext= "Discon tinued "sortexpression=" discontinued "/> </Fields> </asp:DetailsView>

Having made these changes, we have shown the unit price and total amount information in a single DetailsView line.

Figure Eight: Unit price and total amount information is displayed on a separate line.

Step three: Customize the information for the discount field

The Discontinued field of a Products table is a bit value that indicates whether a product is discounted. When a DetailsView (or GridView) is bound to a data source control, a Boolean field (such as discontinued) is implemented as a CheckBoxField rather than a Boolean field (for example, ProductID, ProductName, etc.) will be implemented as BoundField. The CheckBoxField is rendered as a disabled checkbox, and if the value of the data is true, the checkbox is selected, or the state is unchecked.

Rather than displaying a checkboxfield, we might prefer to display it as a text to show whether the product is a discount. To do this, we can delete the CheckBoxField from the DetailsView, add a BoundField, and set its DataField property to discontinued. Well, take some time to finish it! After this change, DetailsView displays a "True" for the discounted product and a "False" for the others.

Figure Nine: String "True" and "False" to show discount status

Think about it, we don't want to use "True" or "False", but rather "YES" and "NO". Such customizations can be implemented by a TemplateField and a formatting method. The formatting method can accept several input parameters, but the intelligence returns an HTML for inserting into the template (string type)

Add a formatting method named Displaydiscontinuedasyesorno to the Detailsviewtemplatefield.aspx page's back code class, which takes a Boolean value as an argument and returns a string. As discussed in the previous section, this method must be marked as protected or public, or it cannot be accessed from the template.

Protected string Displaydiscontinuedasyesorno (bool discontinued)
{
 if (discontinued) return
  "YES";
 else return
  "NO";
}

This method checks the input parameter (whether it is a discount) and returns "YES" if true, otherwise returns "NO".

Note: Recall the relevant content in the previous section, the parameter passed to the format method may be null, so we need to check it for NULL before accessing the employee's hireddate. Such checks are not needed here, because the Discontinued field is never a null value. In addition, this is why this method accepts a Boolean value instead of a Productsrow instance or an object type argument.

After completing this formatting method, the rest is only invoked in the ItemTemplate of TemplateField. To create this TemplateField, we can delete the discontinued bound column and add a new TemplateField, or you can convert discontinued BoundField to TemplateField directly. Then, edit the TemplateField in the source view (the HTML view) so that it contains a itemtemplate that calls the Displaydiscontinuedasyesorno method. Passing parameters are the discontinued properties of the current Productrow instance. This can be accessed through the Eval method. Now, this TemplateField tag code is like this:

<asp:templatefield headertext= "discontinued" sortexpression= "discontinued" >
 <ItemTemplate>
  <%# Displaydiscontinuedasyesorno ((bool)
   Eval ("discontinued")%>
 </ItemTemplate>
</ Asp:templatefield>

Thus, the Displaydiscontinuedasyesorno method is invoked when the DetailsView is rendered, and the discontinued value of the Productrow instance is passed to it. Because the Eval method returns a value of type obejct, and the Displaydiscontinuedasyesorno method accepts only Boolean arguments, we convert the return value of the Eval method to a Boolean. Depending on the value received, the Displaydiscontinuedasyesorno method returns "YES" or "NO", which is what you want to display in this DetailsView row.

Figure 10: "YES" or "NO" is now displayed in the discount line.

Summarize

In DetailsView controls, template columns can handle more complex data rendering than other column controls. Template columns are used primarily for such situations:

• Multiple data columns need to be displayed in a DetailsView column

• Using a Web control to show data is better than a simple piece of text

• The output of the page depends on the data that is bound to the DetailsView, such as metadata or reformatting the data

Although template columns can be highly complex to render DetailsView data, DetailsView input is still a bit awkward because it shows each field as a line of HTML tags <table>.

The FormView control provides a more complex output rendering. FormView does not contain any columns, it only includes a series of templates (ItemTemplate, EditItemTemplate, HeaderTemplate, and so on). In the next section, we'll see how to use FormView to render more controls.

Happy programming!

About the author

Scott Mitchell, with six asp/asp. NET book, is the founder of 4GuysFromRolla.com, has been applying Microsoft Web technology since 1998. Scott is an independent technical consultant, trainer, writer, recently completed a new book to be published by Sams Press, proficient in asp.net 2.0 within 24 hours. His contact email is mitchell@4guysfromrolla.com, or he can contact him through his blog Http://ScottOnWriting.NET.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.