Add Columns dynamically to Grid-view with itemtemplate

前端 未结 1 1838
执念已碎
执念已碎 2020-12-21 08:38

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 awa

1条回答
  •  孤城傲影
    2020-12-21 09:16

    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 page

    
        
    
        
    
    

    You can manipulate DynamicTemplateField class to add different types of control

    0 讨论(0)
提交回复
热议问题