void instantiatein(control container);this method must be implemented in order to decide 'parent' of the template.
using system;using system.web.ui;using system.web.ui.webcontrols;using system.data;namespace dynamicdatagridtemplates{public class ctemplatecolumn:itemplate{ private string colname; public ctemplatecolumn(string cname) { colname=cname; } //must implement following method 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; datagriditem container = (datagriditem) l.namingcontainer; l.text = ((datarowview) container.dataitem)[colname].tostring(); }}}here, the constructor accepts the column name to which we want to bind our templated column. we have created a literal control in the instantiatein method. since our column will be data bound we add ondatabinding event handler that populates the control with the appropriate values. then we add this literalcontrol to the container's controls collection. in the ondatabinding event handler the namingcontainer gives the current datagriditem (since our parent control is datagrid).
datagrid datagrid1=new datagrid();templatecolumn tc1=new templatecolumn();tc1.itemtemplate=new ctemplatecolumn("lastname");tc1.headertext="last name";datagrid1.columns.add(tc1);page.controls[1].controls.add(datagrid1);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");datagrid1.datasource = ds;datagrid1.datamember = "employees";datagrid1.databind();here, we have create instance of datagrid class. we have crerated instance of templatecolumn class. our intention is to add a templated column whose itemtemplate is as decided by our class. hence we set itemtemplate property. in the same manner you can also set edititemtemplate. we have passed the column name (lastname) in the constructor of this class. we then add this column to the datagrid and datagrid to the page. binding of datagrid follows as usual.
新闻热点
疑难解答