如何以编程方式添加gridview的itemtemplate自定义控件

如何以编程方式添加gridview的itemtemplate自定义控件,第1张

动态添加模板列

public class GridViewTextTemplate : System.Web.UI.ITemplate

{

private DataControlRowType templateType

private string columnName

private string Id

public GridViewTextTemplate(DataControlRowType type, string colname, string controlId)

{

templateType = type

columnName = colname

Id = controlId

}

public void InstantiateIn(System.Web.UI.Control container)

{

switch (templateType)

{

case DataControlRowType.Header:

myHeadLiteral.ID = Id

myHeadLiteral.Text = columnName

container.Controls.Add(myHeadLiteral)

break

case DataControlRowType.DataRow:

TextBox txt= new TextBox()

txt.ID = cId

txt.DataBinding += new EventHandler(this.TextBoxDataBinding)

container.Controls.Add(txt)

break

default:

break

}

}

private void TextBoxDataBinding(Object sender, EventArgs e)

{

TextBox txt= (TextBox)sender

GridViewRow row = (GridViewRow)txt.NamingContainer

txt.Text = System.Web.UI.DataBinder.Eval(row.DataItem, columnName).ToString()

}

}

void Page_Load(Object sender, EventArgs e)

{

if (!IsPostBack)

{

TemplateField tf

tf= new TemplateField()

tf.ItemTemplate = new GridViewTextTemplate(DataControlRowType.DataRow, "", "")

tf.HeaderTemplate = new GridViewTextTemplate(DataControlRowType.Header, "", "")

GridView1.Columns.Add(tf)

}

}

我发了一个demo给你,你看看对你有没有用处吧

发件人:150305175@qq.com

这个可以添加int,string等类型的列啊,图中第四列不就是string类型的吗

只不过列标题“选中”与“不选中”时,对应列的效果等等需要你自己在事件中写代码控制


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/bake/11827334.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-19
下一篇2023-05-19

发表评论

登录后才能评论

评论列表(0条)

    保存