【问题标题】:Add Columns dynamically to Grid-view with itemtemplate使用 itemtemplate 将列动态添加到网格视图
【发布时间】:2014-05-11 12:45:48
【问题描述】:

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

【问题讨论】:

    标签: asp.net gridview itemtemplate


    【解决方案1】:

    你需要创建一个实现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 类来添加不同类型的控件

    【讨论】:

    • 添加了动态列,很好。但是如何为每个 itemtemplate 进行绑定并在这种方法中添加新行?
    • 使用 RowDataBound 事件为动态添加的控件赋值,发布的答案会相应编辑
    • 如何触发文本框更改事件并从代码隐藏中保存?
    • txt1.Text = e.Row.DataItem["TestLbl"]; //分配数据源的任何列值我得到错误 - 无法使用 [] 将索引应用于对象类型的表达式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-17
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 2016-03-29
    相关资源
    最近更新 更多