Dynamically create a column in the gridview (2)

Source: Internet
Author: User

· 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. Its keyCodeAs 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 =   " Sqldatasource1 " ;
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)
{< br> 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 =   " Sqldatasource1 " ;
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.

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.