asp.net – 使用itemtemplate动态地将列添加到Grid-view

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

解决方法

您需要创建一个实现ITemplate的类,完整代码如下:
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类以添加不同类型的控件

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....