使用 itemtemplate 将列动态添加到网格视图

编程入门 行业动态 更新时间:2024-10-25 06:27:20
本文介绍了使用 itemtemplate 将列动态添加到网格视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想知道如何将列动态添加到 gridview.网格视图假设获取用户输入.我知道如何将 itemtemplate 用于特定的列数,但我不知道如何使用 itemtemplate(文本框)字段动态添加列并进行数据绑定.

i want to know how to add column dynmically to gridview. the grid view suppose to get user input. i know how to use itemtemplate for specific no of columns, but i'm not aware how to add columns dynamically with itemtemplate (textbox) fields and make databind.

推荐答案

需要创建一个实现ITemplate的类,完整代码如下:

You need to create a class implementing ITemplate , Full code as following:

public class DynamicTemplateField : ITemplate
{

    public void InstantiateIn(Control container)
    {
        //define the control to be added , i take text box as your need
        TextBox txt1 = new TextBox();
        txt1.ID = "txt1";
        container.Controls.Add(txt1);
    }
}

//Method to bind the Grid View
public void BindData()
{
    TemplateField temp1  = new TemplateField();  //Create instance of Template field
    temp1.HeaderText = "New Dynamic Temp Field"; //Give the header text

    temp1.ItemTemplate = new DynamicTemplateField(); //Set the properties **ItemTemplate** as the instance of DynamicTemplateField class.


    gv.Columns.Add(temp1); //add the instance if template field in columns of grid view

    //Bind the grid  view
    gv.DataSource = [your data source];
    gv.DataBind();

 }

RowDataBound

protected void gv_RowDataBound(object sender, System.Web.UI.WebControls.GridViewRowEventArgs e)
{
  if(e.Row.RowType == DataControlRowType.DataRow)
   {
      TextBox txt1 = e.Row.FindControl("txt1") as TextBox;
      txt1.Text = e.Row.DataItem["Name"]; //Assign any column value of your datasource
    }

}

.aspx 页面

<asp:GridView ID = "gv" runat = "server"  >
    <Columns>

    </Columns>
</asp:GridView>

您可以操纵DynamicTemplateField 类来添加不同类型的控件

You can manipulate DynamicTemplateField class to add different types of control

这篇关于使用 itemtemplate 将列动态添加到网格视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

更多推荐

[db:关键词]

本文发布于:2023-04-01 10:41:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/828286.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:网格   视图   动态   itemtemplate

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!