templatefield 动态_动态添加TemplateField列

本文介绍了如何在ASP.NET GridView中使用GridViewTextTemplate类创建自定义的Header和DataRow模板,以及如何动态添加TemplateField并设置数据绑定。通过实例展示了如何根据不同的数据类型生成相应的表头和数据单元格。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

GridViewTextTemplate类:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI.WebControls;

///

///GridViewTextTemplate 的摘要说明

///

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 = "" + columnName + "";

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", "") });

分享到:

18e900b8666ce6f233d25ec02f95ee59.png

72dd548719f0ace4d5f9bca64e1d7715.png

2012-10-23 15:03

浏览 153

评论

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值