GridViewTextTemplate类:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI.WebControls; /// <summary> ///GridViewTextTemplate 的摘要说明 /// </summary> public class GridViewTextTemplate : System.Web.UI.ITemplate { private DataControlRowType templateType; private string columnName; private string cId; public GridViewTextTemplate(DataControlRowType type, string colname, string controlId) { templateType = type; columnName = colname; cId = controlId; } public void InstantiateIn(System.Web.UI.Control container) { // Create the content for the different row types. switch (templateType) { case DataControlRowType.Header: // Create the controls and set id properties to put in the header Literal myHeadLiteral = new Literal(); myHeadLiteral.ID = cId; myHeadLiteral.Text = "<B>" + columnName + "</B>"; container.Controls.Add(myHeadLiteral); break; case DataControlRowType.DataRow: // Create the controls and set id properties to put in a data row TextBox myTextBox = new TextBox(); myTextBox.ID = cId; myTextBox.DataBinding += new EventHandler(this.TextBoxDataBinding); myTextBox.Width = 100; container.Controls.Add(myTextBox); break; default: // Insert code to handle unexpected values. break; } } private void TextBoxDataBinding(Object sender, EventArgs e) { TextBox myTextBox = (TextBox)sender; GridViewRow row = (GridViewRow)myTextBox.NamingContainer; myTextBox.Text = System.Web.UI.DataBinder.Eval(row.DataItem, columnName).ToString(); } }在后台GridView动态添加TemplateField:
//parameter_description绑定的数据 textParameterDesc是Text的ID TemplateField tField; tField = new TemplateField(); tField.HeaderTemplate = new GridViewTextTemplate(DataControlRowType.Header, "说明", "textParameterDescHd"); tField.ItemTemplate = new GridViewTextTemplate(DataControlRowType.DataRow, "parameter_description", "textParameterDesc"); GridView1.Columns.Add(tField);或者:
GridView1.Columns.Add(new TemplateField() { HeaderTemplate = new GridViewTextTemplate(DataControlRowType.Header, "序号", ""), ItemTemplate = new GridViewTextTemplate(DataControlRowType.DataRow, "PlanSN", "") });