system.object system.web.ui.control system.web.ui.templatecontrol system.web.ui.pagethe system.web.ui.templatecontrol class contains a method called loadtemplate that can be used to dynamially load temlates for templated controls. the signature of loadtemplate is like this:
public itemplate loadtemplate(string virtualpath);the method takes virtual path of a user control file i.e. .ascx file.
<%@ control language="c#" %><asp:label id="label1" runat="server" text='<%# databinder.eval(ctype(container,datagriditem).dataitem,"lastname")%>'></asp:label>note that this markup looks same as if we would have used it in design mode. here, we are binding a label control with the lastname field from the datamember.
string connstr = @"integrated security=sspi;user id=sa;initial catalog=northwind;data source=myserver/netsdk";sqlconnection cnn=new sqlconnection(connstr);sqldataadapter da=new sqldataadapter("select * from employees", cnn)dataset ds=new dataset();da.fill(ds, "employees");itemplate temp= page.loadtemplate("webusercontrol1.ascx");templatecolumn tc=new templatecolumn();tc.headertext = "last name";tc.itemtemplate = temp;datagrid1.columns.add(tc);datagrid1.datasource = ds;datagrid1.datamember = "employees";datagrid1.databind();most of the code will be familiar to you except code related to itemplate. we have loaded our template using loadtemplate method. we then create a templatecolumn and set its itemtemplate to it. even though we have used itemtemplate, it can be any other type of template also like edititemtemplate. we then add this new column to the datagrid. note that our datagrid instance datagrid1 is declared at class level and hence not visible in the code shown above.
新闻热点
疑难解答