[Translation] dynamically create a column in the GridView (Part 2)

Source: Internet
Author: User
Original address: http://www.dotnetbips.com/articles/displayarticledetails.aspx? Articleid = 521
[Source code download]
[Download the source code after the translator changes it]

[Translation] dynamically create a column in the GridView (Part 2)

Original article released on: 2006.11.24
Author: Bipin Joshi
Translation: webabcd

Introduction
In the first part, you learned how to dynamically create BoundField and CommandField. However, the columns you construct often do not meet the requirements, so you need to use TemplateField. For example, if you want to create a product directory, you can certainly use a standard layout, but this is not appropriate if you want each record to have a highly customized format. In this case, you can manually modify the format of TemplateField. This article illustrates how to dynamically create a TemplateField. You will learn the following two technologies:

· Use LoadTemplate () method
· Create a custom template Column

Use LoadTemplate () to add TemplateField
To implement this example, you need to create a websit in Visutal Studio. Drag a GridView and SqlDataSource to the detail page. We will encode some column attributes of these controls. First, we will use the LoadTemplate () method to add a TemplateField. The LoadTemplate () method is available for all template controls on the page. It loads a template through a virtual path. The returned value of LoadTemplate () is an object that implements the ITemplate interface.

In our example, we will create a template in the user control. Create a user control named ItemTemplate. ascx in the website. The key code is as follows. <% @ Control Language = "C #" AutoEventWireup = "true" CodeFile = "ItemTemplate. ascx. cs" Inherits = "ItemTemplate" %>
<Asp: Label ID = "Label1" runat = "server" Text = '<% # Eval ("EmployeeID") %>'> </asp: Label>
<Asp: Label ID = "Label2" runat = "server" Text = '<% # Eval ("FirstName") %>'> </asp: Label>
<Asp: Label ID = "Label3" runat = "server" Text = '<% # Eval ("LastName") %>'> </asp: Label>

Take a closer look at the above mark. It contains three Label controls. The Text attribute of each Label control is bound to the EmployeeID, FirstName, and LastName columns of the Employees table. The Eval () expression is a data binding method in asp.net, which uses the column name to bind. This user control will be used in our ItemTemplate later.

Now, the default webform code editing window is opened. The key code in its Page_Load event is as follows. Protected void Page_Load (object sender, EventArgs e)
{
SqlDataSource1.ConnectionString = @ "data source =.; initial catalog = northwind; integrated security = true ";
SqlDataSource1.SelectCommand = "select employeeID, FirstName, LastName from employees ";

If (! IsPostBack)
{
Gridview1.performanceid = "sqlperformance1 ";
GridView1.AutoGenerateColumns = false;

TemplateField tf1 = new TemplateField ();
Tf1.ItemTemplate = LoadTemplate ("ItemTemplate. ascx ");
GridView1.Columns. Add (tf1 );
}
}

This Code indicates that the ConnectionString attribute of the SQL data source control is connected to the Northwind database. Its SelectCommand attribute is specified as a select query statement. It retrieves the columns of EmployeeID, FirstName, and LastName from the Employees table. Then, the performanceid attribute of the GridView is set to the ID of the data source control. At the same time, the AutoGenerateColumns attribute is set to false to dynamically add columns. The following lines of code are very important. First, instantiate a TemplateField class, which can be displayed as a TemplateColumn of the GridView. Set the ItemTemplate attribute of the TemplateField class to the return value of the LoadTemplate () method. The LoadTemplate () method uses a virtual path to load the template (in our example, the template file is ItemTemplate. ascx ). Add the TemplateField to the column set of the GridView control.

Running this webform in your browser will be shown as follows.

Pay attention to how to apply the template specified in the user control. At the same time, we can see that the title is empty because HeaderTemplate is not specified. You can specify or disable it.

Add TemplateField with custom template class
Now you know how to use the LoadTemplate () method. Let's take a look at how to use another method. In the final example, you learned to use the LoadTemplate () method to return an object that implements the Itemplate interface. You can also create a class that implements the Itemplate interface and use it directly to replace the LoadTemplate () method.

Create a class named MyTemplate in the App_Code folder. The key code is as follows. Public class MyTemplate: ITemplate
{
Private string colname;

Public MyTemplate (string colname)
{
This. colname = colname;
}

Public void InstantiateIn (Control container)
{
LiteralControl l = new LiteralControl ();
L. DataBinding + = new EventHandler (this. OnDataBinding );
Container. Controls. Add (l );
}

Public void OnDataBinding (object sender, EventArgs e)
{
LiteralControl l = (LiteralControl) sender;
GridViewRow container = (GridViewRow) l. NamingContainer;
L. Text = (DataRowView) container. DataItem) [colname]. ToString ();
}
}

This Code creates a class that implements the Itemplate interface named MyTemplate. This interface contains only one method you must implement-InstantiateIn (). This Code declares a variable used to save the name of the displayed column, which is set in the constructor of the class, and then implements the InstantiateIn () method. The parameters of this method are the objects of controls of the container type or parent control type. Here, we create a LiteralControl and a DataBinding event (OnDataBinding ). This event occurs when the container control calls the DataBind () method. Add the LiteralControl to the control set of the Container Control.

The OnDataBinding () event binds the required data to LiteralControl. Add the NamingContainer attribute to the Container Control and extract a Row. Finally, the Text attribute of LiteralControl is set to the value stored in the database for the column pointed out by the constructor. In this way, our custom template class is complete.

Create a webform in the website. Drag a GridView and SqlDataSouce to the page as before. The Code in its Page_Load event is as follows. Protected void Page_Load (object sender, EventArgs e)
{
SqlDataSource1.ConnectionString = @ "data source =.; initial catalog = northwind; integratedsecurity = true ";
SqlDataSource1.SelectCommand = "select employeeID, FirstName, LastName from employees ";

If (! IsPostBack)
{
Gridview1.performanceid = "sqlperformance1 ";
GridView1.AutoGenerateColumns = false;

TemplateField tf1 = new TemplateField ();
MyTemplate t1 = new MyTemplate ("FirstName ");
Tf1.HeaderText = "First Name ";
Tf1.ItemTemplate = t1;

TemplateField tf2 = new TemplateField ();
MyTemplate t2 = new MyTemplate ("LastName ");
Tf2.HeaderText = "Last Name ";
Tf2.ItemTemplate = t2;

GridView1.Columns. Add (tf1 );
GridView1.Columns. Add (tf2 );
}
}

This Code sets the properties of the GridView and SqlDataSource as before. Note that the bold part in the Code (the lower part of the Code) is used to create the entity of the TemplateField class. The ItemTemplate attribute of TemplateField is set to the instantiated MyTemplate class. The column names FirstName and LastName are passed to the constructor. TemplateField is added to the column set of the GridView.

Run the webform shown below.

This article is complete! Happy coding.

Author: Bipin Joshi
Email: http://www.dotnetbips.com/contact.aspx
Overview: Bipin Joshi is the administrator of DotNetBips.com. He is the initiator of http://www.binaryintellect.com/. he is the training and consulting service of this company's .net framwork. He provides developers with training in Mumbai, India. He is also a member of Microsoft MVP (ASP. Net) and ASPInsiders.

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.