Use TemplateField to display the metadata of data in the GridView

Source: Internet
Author: User

The third method of TemplateField is to display the metadata of data in the GridView. For example, in addition to displaying the employee's employment date, we may also want to use a column to show how long the employee has been working in the company.

There is also a usage that will be used in some cases. For example, the display format of a data on the page needs to be different from the storage format in the database. Imagine that there is a gender field in the employee table, which stores characters such as M or F to indicate whether the employee is male or female. When we need to display this information on the page, we may want to display it as "male" or "female" rather than "M" or "F ".

Both methods can be used in ASP. the post-code class of the NET page, or implement it as a static method in an independent class library) create a formatting method called by the template. This formatting method will be called in the template. The syntax is the same as the preceding data binding syntax. The formatting method can accept several parameters, but must return a string. The returned string is an HTML used to insert to the template.

Let's add something to illustrate this concept. Add a column to show the number of days employees work in the company. This formatting method accepts a Northwind. EmployeesRow object and returns the number of days this employee has been working in the company in the form of a string. This method can be added to the post code class on the ASP. NET page, but remember to mark it as protected or public, otherwise the template will not be able to access it.

 
 
  1. Protected StringDisplayDaysOnJob (Northwind. EmployeesRow employee)
  2. {
  3. // Make sure that HiredDate is not empty ...... If it is null, "Unknown" is returned" 
  4. If(Employee. IsHireDateNull ())
  5. Return "Unknown";
  6. Else 
  7. {
  8. // Returns the number of days between the current date and HireDate. 
  9. TimeSpan ts = DateTime. Now. Subtract (employee. HireDate );
  10. ReturnTs. Days. ToString ("#,## 0");
  11. }

Because HiredDate may contain null values, we must first ensure that the value is not empty before calculation. If the value of HiredDate is null, an "Unknown" is returned. If it is not null, the number of days between the current time and the value of HiredDate is calculated, and return it as a string.

To use this method, we need to use the data binding syntax in the TemplateField of the GridView to call it. Similarly, we should add a new template column to the GridView first.

TemplateField: Add a new template column to the GridView.

Set the header text HeaderText of the new template column to "Days on the Job", and horizontally align its ItemStyle with HorizontalAlign) to Center ). To call the DisplayDaysOnJob method, we need to add an ItemTemplate to this template column and add the following data binding code:

 
 
  1. < %# DisplayDaysOnJob((Northwind.EmployeesRow) ((System.Data.DataRowView) Container.DataItem).Row) %>    

Container. DataItem returns a corresponding DataRowView object in the data source object to the GridView. Its Row attribute returns a strongly typed Nothwind. EmployeesRow, and then passes it to the DisplayDaysOnJob method. The Data Binding syntax can directly display the Text attribute assigned to the Label control in the ItemTemplate as in the code below.

Note: Apart from passing an EmployeesRow instance, we can also pass only the HireDate value by using <% # DisplayDaysOnJob (Eval ("HireDate") %>. However, the Eval method returns an object type, so we must modify the DisplayDaysOnJob method signature so that it can accept an object type parameter. The call results of Eval ("HireDate") cannot be implicitly converted to a DateTime type, because the HireDate field of the Employees table can be empty. Therefore, we need to make the DisplayDaysOnJob method accept an object-type parameter and determine whether the parameter is null. We can use Convert. isDBNull (objectToCheck) to complete this verification), and then perform subsequent operations. 

Because of this, I chose to pass the entire EmployeesRow instance. In the next tutorial, we will see an example that is more suitable for passing parameters to the formatting method using Eval ("columnName.

After the template column is added to the GridView and the code that calls the DisplayDaysOnJob method is added to the ItemTemplate, the declaration code should look like this:

 
 
  1. < asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"   
  2. DataKeyNames="EmployeeID" 
  3.     DataSourceID="ObjectDataSource1">  
  4.      < Columns>  
  5.          < asp:TemplateField HeaderText="Name" SortExpression="FirstName">  
  6.              < EditItemTemplate>  
  7.                  < asp:TextBox ID="TextBox1" runat="server" Text='< %# Bind("FirstName") %>'>  
  8. < /asp:TextBox>  
  9.              < /EditItemTemplate>  
  10.              < ItemTemplate>  
  11.                  < asp:Label ID="Label1" runat="server" Text='< %# Bind("FirstName") %>'>< /asp:Label>  
  12.                 < asp:Label ID="Label2" runat="server" Text='< %# Eval("LastName") %>'>< /asp:Label>  
  13.             < /ItemTemplate>  
  14.         < /asp:TemplateField>  
  15.         < asp:BoundField DataField="Title" HeaderText="Title" SortExpression="Title" />  
  16.         < asp:TemplateField HeaderText="HireDate" SortExpression="HireDate">  
  17.             < EditItemTemplate>  
  18.                 < asp:TextBox ID="TextBox2" runat="server" Text='< %# Bind("HireDate") %>'>  
  19. < /asp:TextBox>  
  20.             < /EditItemTemplate>  
  21.             < ItemTemplate>  
  22.                 < asp:Calendar ID="Calendar1" runat="server" SelectedDate='< %# Bind("HireDate") %>' 
  23.                     VisibleDate='< %# Eval("HireDate") %>'>< /asp:Calendar>  
  24.             < /ItemTemplate>  
  25.         < /asp:TemplateField>  
  26.         < asp:TemplateField HeaderText="Days On The Job">  
  27.             < ItemTemplate>  
  28.                 < %# DisplayDaysOnJob((Northwind.EmployeesRow) ((System.Data.DataRowView)  
  29.  Container.DataItem).Row) %>  
  30.             < /ItemTemplate>  
  31.             < ItemStyle HorizontalAlign="Center" />  
  32.         < /asp:TemplateField>  
  33.     < /Columns>  
  34. < /asp:GridView> 

After completing the tutorial, the page should look like this in the browser, as shown in Figure 16.

 

TemplateField: "How long have employees been working in the company ?"

  1. Use ASP. NET DetailsView to display details
  2. Familiar with the use of DropDownList and ObjectDataSource
  3. ASP. NET DropDownList creation and filling
  4. Use the GridView and ObjectDataSource in ASP. NET
  5. Example of ASP. NET DropDownList

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.