Manipulating data 12 in asp.net 2.0: Using the Templatefield_ self-study process in the GridView control

Source: Internet
Author: User
Tags datetime eval

Introduction

The GridView consists of a set of fields (field) that specify what attributes from the DataSource need to be used in their own output rendering. The simplest type of field is BoundField, which simply displays the data as text. Other field types use interactive HTML elements (alternate HTML elements) to display data. For example, CheckBoxField will be rendered as a checkbox whose selection is determined by the value of a particular data field; ImageField renders a particular data field as a picture, and of course, the data field should be in the form of a picture type. The status of hyperlinks and buttons depends on the value of the data field using the HyperLinkField or ButtonField field type.

Although CheckBoxField, ImageField, HyperLinkField, and ButtonField take into account the interactive view of the data, they still have some formatting limitations. CheckBoxField can only be displayed as a single checkbox, while a ImageField can only be displayed as one picture. What do we do when a field shows some text, check boxes, pictures, and other things based on different data? Or, what if we need to use a Web control other than the checkbox, Image, Hyperlink, and button to display the data? In addition, BoundField can only display a single data field. What if we want to display the values of two or more data fields in a GridView column?

To accommodate such a complex situation, the GridView provides a templatefield for rendering using templates. Templates can include static HTML, Web controls, and data-bound code. In addition, TemplateField has a variety of templates that can be used for page rendering in different situations. For example, ItemTemplate is the default for rendering cells in each row, while EditItemTemplate is used to customize the interface when editing data.

In this tutorial, we will explain how to use TemplateField to customize the GridView control more advanced. In the previous tutorial, we saw how to use the DataBound and RowDataBound event-handling methods to customize data-based formatting. Another option is to call a formatting method in the template. In this section, we will see this technique.

In this section, we will use some TemplateField to customize the rendering of employee information. In particular, we will list all the employees, but we will put the employee's last name and name in a column, put their hire date in a Calendar control, and will use a status column to show how long they have come to the company.

Figure I: Using three TemplateField to customize the way information is displayed

First step: Bind data to the GridView

When you need to use some TemplateField to customize the display, I find it easiest to create a GridView control that contains only BoundField, and then add some templatefield, if necessary, Some BoundField can also be converted directly to TemplateField. OK, let's start this tutorial. First, you add a GridView control to the page through the designer and bind a ObjectDataSource that returns employee information to it. These steps create a GridView with some BoundField that correspond to the different fields in the employee information. BoundField

Open gridviewtemplatefield.aspx and drag a GridView from the toolbox to the designer. Select and add a new ObjectDataSource control that invokes the GetEmployees () method of the Employeesbll class from the GridView smart Tag (smart tag).

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

Binding the GridView in this way automatically adds a Boundfield:employeeid, LastName, FirstName, Title, HireDate, ReportsTo, and country to each property of the employee's information. In this report, we don't want to see the EmployeeID, ReportsTo, and country properties. To remove these BoundField, you can:

• Use the Field dialog box-click Edit Columns in the pop-up menu of the GridView smart tag. Then, in the lower left-hand corner of the list, select the BoundField you want to delete and click the button with the Red Fork to remove the BoundField.

• Manually edit the declaration statement of the GridView-in Source view, find the BoundField you want to delete, that is, the <asp:BoundField> elements, delete the line.

After you have deleted the BoundField of EmployeeID, ReportsTo and country, the markup language code for your gridview should look like this:

<asp:gridview id= "GridView1" runat= "Server"
 autogeneratecolumns= "False" datakeynames= "EmployeeID
 " Datasourceid= "ObjectDataSource1" >
 <Columns>
 <asp:boundfield datafield= "LastName" headertext= "LastName"
  sortexpression= "LastName"/> <asp:boundfield datafield= "FirstName" headertext=
 "
  sortexpression=" FirstName "/>
 <asp:boundfield datafield=" title "headertext=" title
  " sortexpression= "Title"/>
 <asp:boundfield datafield= "
  hiredate" headertext= "HireDate" sortexpression= "HireDate"/>
 </Columns>
</asp:GridView>

Let's take some time to look at our results in the browser. At this point, you will see a table in which each record is an employee's information, a total of four columns: one is the employee's surname, one is the name, one is the title, and one is the date of their employment.

Figure three: Each employee information shows the LastName, FirstName, title and HireDate

Step Two: Display the first and last names in a column

The first and last names of each employee are now displayed separately in two columns. It might be a good idea to put them in a column and show them. To do this, we need to use TemplateField. We can add a new TemplateField, give it some necessary markup language and data binding code, and then delete the original FirstName and LastName these two BoundField; of course, We can also convert FirstName this BoundField directly into a TemplateField, edit it to add LastName value, and then delete LastName this BoundField.

Either way, but I personally prefer the one that's directly converted, because it automatically adds ItemTemplate and EditItemTemplate that contain Web controls and corresponding data-binding code. They can be used to mimic the rendering and function of a boundfield. The benefits of doing so naturally are self-evident, because the process of conversion has helped us do a lot of things, then of course we can save a lot of time.

To convert a BoundField to TemplateField, we can click Edit Columns in the pop-up menu of the GridView smart tag. In the lower left corner of the pop-up dialog box, select the BoundField you want to convert, and then click "Convert this column to template column" in the lower-right corner (convert this field to a TemplateField).

Figure Four: In the Field dialog box, convert a bound column to a template column

Let's continue to convert FirstName this boundfield into TemplateField. After this change, there is no obvious difference in the designer. This is because converting BoundField into TemplateField is actually creating a TemplateField that maintains the look and feel of the previous BoundField. Although there is no visual change in the designer, this conversion process has--<asp:boundfield the BoundField declaration code datafield= "FirstName" headertext= "FirstName" The sortexpression= "FirstName"/>--changed to the TemplateField declaration code shown below:

<asp:templatefield headertext= "FirstName" sortexpression= "FirstName" >
 <EditItemTemplate>
 <asp:textbox id= "TextBox1" runat= "server" text=
  ' <%# Bind ("FirstName")%> ' ></asp:TextBox>
 </EditItemTemplate>
 <ItemTemplate>
 <asp:label id= "Label1" runat= "Server"
  text= " <%# Bind ("FirstName")%> ' ></asp:Label>
 </ItemTemplate>
</asp:TemplateField>

As you can see, TemplateField consists of two templates--a ItemTemplate that has a label control whose Text property is set to the value of the FirstName data field; and a EditItemTemplate, It has a Textbix control and its Text property is set to the value of the FirstName data field. The data binding syntax--<%# bind ("FieldName")%>--the Description data field FieldName is bound to the properties of this particular Web control.

To add LastName to TemplateField, we need to add a Label control for ItemTemplate and bind its Text property to LastName. This can be done either through the designer or by hand-written code. To write code manually, simply add the corresponding declaration code to the ItemTemplate, as follows:

<asp:templatefield headertext= "FirstName" sortexpression= "FirstName" >
 <EditItemTemplate>
 <asp:textbox id= "TextBox1" runat= "server" text=
  ' <%# Bind ("FirstName")%> ' ></asp:TextBox>
 </EditItemTemplate>
 <ItemTemplate>
 <asp:label id= "Label1" runat= "Server"
  text= " <%# Bind ("FirstName")%> ' ></asp:Label> <asp:label id= ' Label2 ' runat= '
 server '
  text= ' <% # Bind ("LastName")%> ' ></asp:Label>
 </ItemTemplate>
</asp:TemplateField>

To add it through the designer, click Edit Templates in the pop-up menu of the GridView smart tag. This displays the template editing interface for the GridView. In this interface, the smart tag is a list of templates in the GridView. Because we only have one templatefield at this time, the dropdown list only has FirstName templates and EmptyDataTemplate and PagerTemplate.

If the emptydatatemplate template is specified, it will be used to render the output rendering when there are no records in the data source of the GridView, and if PagerTemplate is specified, it will be used to render the GridView's paging interface.

Figure Five: The template columns for the GridView can be edited through the designer

To display LastName in the FirstName template column, drag a label from the Toolbox to the ItemTemplate of the FirstName template column, which, of course, is done in the template editing interface of the GridView, as shown in the following illustration:

Figure VI: Add a label to the ItemTemplate of the FirstName template column

Now, the Text property of the label control added to the TemplateField or "label". We need to modify this so that this property is bound to the LastName field in the data source. We can click on the label control's smart tag, and then select the Edit DataBindings option in the pop-up menu, as shown in the following illustration:

Figure VII: Select the Edit DataBindings option from the label's smart tag

In the Data-binding dialog box that pops up, you can select the property you want to bind in the list on the left, and then select a data field in the down box to the right. OK, now we're going to select the Text property on the left, then select the LastName field on the right and click OK.

Figure Eight: Binding the Text property to the LastName field

Note: The Data Binding dialog box allows you to declare a two-way data binding. If you keep the "two-way data binding" (Two-way databinding) check box unchecked, the data-bound code will be <%# Eval ("LastName")%> rather than <%# bind ("LastName ")%>. However, for the tutorial in this section, the results of two practices are OK. Bidirectional data binding will be more important when inserting and editing data. But if it's just a simple display of data, both approaches are the same. We will discuss two-way data binding in detail in future chapters.

Let's take some time to look at this page in the browser. As you can see, the GridView still contains 4 columns, but the FirstName column shows the last name and two data.

Figure nine: The last name and first name appear in the same column.

To complete this step, we first remove the LastName binding column and change the column header text (HeaderText) of the FirstName template column to "Name". After that, the GridView Declaration code will look like this:

<asp:gridview id= "GridView1" runat= "Server"
 autogeneratecolumns= "False" datakeynames= "EmployeeID
 " Datasourceid= "ObjectDataSource1" >
 <Columns>
 <asp:templatefield headertext= "Name" sortexpression= "FirstName" >
  <EditItemTemplate>
  <asp:textbox id= "TextBox1" runat= "Server"
   text= ' <%# Bind ("FirstName")%> ' ></asp:TextBox>
  </EditItemTemplate>
  < itemtemplate>
  <asp:label id= "Label1" runat= "server" text=
   ' <%# Bind ("FirstName")%> ' ></ asp:label>
  <asp:label id= "Label2" runat= "server" text=
   ' <%# Eval ("LastName")%> ' ></asp: label>
  </ItemTemplate>
 </asp:TemplateField>
 <asp:boundfield datafield= "Title" headertext= "title"
  sortexpression= "title"/>
 <asp:boundfield datafield= "HireDate" HireDate "
  sortexpression=" HireDate "/>
 </Columns>
</asp:GridView>

Figure 10: The first and last names of each employee are displayed in the same column.

Step three: Use the Calendar control to display the Hireddate field

To display the data as text in the GridView, you simply need to use BoundField. However, on certain occasions, the data is best presented as a special Web control rather than as a simple text. This kind of custom data display can be done with TemplateField. For example, rather than displaying the employee's employment date as text, we find it much more refreshing to highlight it in a calendar (using the Calendar control).

To do this, first convert the hireddate bound column to a template column. As before, the conversion is, we should not forget it? Just do it on the smart tag of the GridView.

Figure 11: Converting the Hireddate bound column into a template column

As we saw in the second step, this action replaces the bound column with a template column that contains ItemTemplate and EditItemTemplate. The ItemTemplate and EditItemTemplate are respectively provided with a label and a textbox, and the Text property of the label and TextBox uses the data-binding statement <%# bind ("Hireddate") %> to bind HireDate to himself.

To replace this text with the Calendar control, we can edit the template: Delete the Label control and add the last Calendar control. In the designer, select Edit Template from the pop-up menu of the GridView smart tag and select the ItemTemplate for the HireDate template column in the Drop-down list. Then, delete the label control and drag a Calendar control from the Toolbox to the template editing interface.

Figure 12: Add a Calendar control to the ItemTemplate of the HireDate template column

At this time, the HireDate template column for each row in the GridView contains a calendar control. However, the actual hire date for the employee is not yet set on the Calendar control, which allows the calendar control to appear by default as the current date. We can fix this problem by assigning the employee's hiredate to the SelectedDate and VisibleDate properties of the Calendar control.

Select Edit data binding from the smart tag of the Calendar control. Then, bind both the SelectedDate and VisibleDate properties to the HireDate field.

Figure 13: Bind the SelectedDate and visibledate to the HireDate field

Note: The Calendar control's selected date is not necessarily visible. For example, a calendar control has a selected date of April 1, 1999, but it shows the current year. The selected date and visible date are specified by the SelectedDate and VisibleDate properties of the Calendar control. Because not only do we want to select the employee's hiredate, but we want it to be visible, we need to bind both properties to the HireDate field.

Now, let's look at this page in the browser, and the calendar now shows the month of the employee's employee's date of employment and a specified date is selected.

Figure 14: The employee's date of employment is displayed on the Calendar control

Note: In contrast to the examples we have been seeing, we have not set the EnableViewState property of the GridView to False in this tutorial. The reason for this is that clicking on the Calendar control produces a postback (postback) and sets the selected date of the calendar to the date that was clicked. If the viewstate of the GridView is disabled, each postback will cause the GridView to rebind with the original data so that the selected date of the calendar becomes the original employee's date of employment.

In this tutorial, this is a meaningless issue because the user should not be able to modify the employee's employment date. It may be best to configure the Calendar control directly as an option. However, as you can see in this tutorial, in some cases it is also possible to enable the control's viewstate to provide certain functionality.

Step Fourth: Show how many days employees have worked in the company

By now, we have seen two applications of TemplateField:

• Merge two data into one column

• Use a Web control to display data instead of using a simple text

The third type of TemplateField is to display the metadata for the data in the GridView. For example, in addition to showing the employee's employment date, we might also want to use a column to show how long the employee has worked in the company.

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

Both usages can be done by creating a format method (formatting) for template invocation in the back code class of the ASP.net page (or in a separate class library to implement it as a static method). Such a formatting method is called in the template, and the syntax is the same as the previous data-binding syntax. The formatting method can accept several parameters, but it must return a string. This returned string is an HTML used to insert into the template.

Let's add a little bit of content to illustrate this concept. The main is to add a column to show the number of days employees work in the company. This formatting method takes a Northwind.employeesrow object and returns the number of days that the employee worked in the company as a string. This method can be added to the back code class of the ASP.net page, but be sure to mark it as protected or public, otherwise the template will not be able to access it.

Protected string Displaydaysonjob (Northwind.employeesrow employee)
{
 //Make sure hireddate are not null ... if so, Return "Unknown"
 if (employee. Ishiredatenull ()) return
 "Unknown";
 else
 {
 //Returns The number of days between the current
 //Date/time and hiredate
 TimeSpan ts = DateTime. Now.subtract (employee. HireDate);
 Return TS. Days.tostring ("#,# #0");
 }

Since hireddate may contain null values, we must first guarantee that the value is not null before making the calculation. If the Hireddate value is empty, return directly to a "Unknown" or, if not empty, calculate the number of days between the current time and the Hireddate value 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 invoke it. Again, we're going to add a new template column to the GridView.

Figure 15: Adding a new template column to the GridView

Set the header text (HeaderText) of this new template column to "Days on the Job" and set its ItemStyle horizontal alignment (horizontalalign) to Center (center). To invoke the Displaydaysonjob method, we need to add a ItemTemplate to the template column and add the following data binding code:

<%# 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 property returns a strongly typed Nothwind.employeesrow, which is then passed to the Displaydaysonjob method. This data-binding syntax can appear directly in the ItemTemplate (as in the following code) or the Text property assigned to a label control.

Note: In addition to passing a Employeesrow instance, we can actually simply pass the HireDate value and use <%# displaydaysonjob (Eval ("HireDate"))%>. However, the Eval method returns an object type, so we have to modify the signature of the Displaydaysonjob method so that it can accept an argument of type object. We cannot implicitly convert the result of the eval ("HireDate") call to a DateTime type because the HireDate field of the Employees table is allowed to be empty. Therefore, we need to enable the Displaydaysonjob method to accept an object type parameter and determine whether the parameter is null (we can use Convert.isdbnull (Objecttocheck) to complete this validation), Then proceed to the subsequent operation.

That's why I chose to pass the whole Employeesrow instance. In the next tutorial, we see an example of a more appropriate use of eval ("ColumnName") to pass parameters to the formatting method.

After adding the template column to our GridView and adding the code that calls the Displaydaysonjob method in ItemTemplate, the declaration code should look like this:

<asp:gridview id= "GridView1" runat= "Server" autogeneratecolumns= "False" datakeynames= "EmployeeID" datasourceid= " ObjectDataSource1 "> <Columns> <asp:templatefield headertext=" Name "sortexpression=" FirstName "> < edititemtemplate> <asp:textbox id= "TextBox1" runat= "server" text= ' <%# Bind ("FirstName")%> ' ></asp: textbox> </EditItemTemplate> <ItemTemplate> <asp:label id= "Label1" runat= "server" text= ' <%# Bind ("FirstName")%> ' ></asp:Label> <asp:label id= "Label2" runat= "Server" text= "<%# Eval (" LastName " )%> ' ></asp:Label> </ItemTemplate> </asp:TemplateField> <asp:boundfield datafield= ' Title "headertext=" title "sortexpression=" title "/> <asp:templatefield headertext=" hiredate "sortexpression=" HireDa TE "> <EditItemTemplate> <asp:textbox id=" TextBox2 "runat=" server "text= ' <%# ' Bind (" HireDate ")%> ' & Gt;</asp:textbox> </edititemtemplate> <ItemTemplate> <asp:calendar id= "Calendar1" runat= "server" Selecteddate= ' <%# Bind ("Hireda TE ")%> ' visibledate= ' <%# Eval (" HireDate ")%> ' > </asp:Calendar> </ItemTemplate> </asp:t emplatefield> <asp:templatefield headertext= "Days on the Job" > <ItemTemplate> <%# displaydaysonjob ( (Northwind.employeesrow) ((System.Data.DataRowView) Container.DataItem). Row)%> </ItemTemplate> <itemstyle horizontalalign= "Center"/> </asp:TemplateField> </column S> </asp:GridView>

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

Figure 16: "How long have employees worked in the company" is also shown

Summarize

In the GridView control, 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 GridView 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 GridView, such as metadata or reformatting the data

In addition to customizing the display of data, the template column is also used to customize the user interface when editing and inserting data, as we'll see in later chapters.

In the next two sections, we'll continue with the discussion of templates, and we'll look at the use of template columns in DetailsView. Then we'll look at FormView, which is using a template to achieve a more complex rendering, of course, with a lot of fields.

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.