Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/34.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Asp.net 使用itemtemplate将列动态添加到网格视图_Asp.net_Gridview_Itemtemplate - Fatal编程技术网

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

Asp.net 使用itemtemplate将列动态添加到网格视图,asp.net,gridview,itemtemplate,Asp.net,Gridview,Itemtemplate,我想知道如何将列动态添加到gridview。假设网格视图获取用户输入。我知道如何对特定数量的列使用itemtemplate,但不知道如何使用itemtemplate(textbox)字段动态添加列并进行数据绑定 您需要创建一个实现ITemplate的类,完整代码如下: public class DynamicTemplateField : ITemplate { public void InstantiateIn(Control container) { //d

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

您需要创建一个实现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();

 }
行数据绑定

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事件为动态添加的控件赋值,发布的答案将根据情况进行编辑如何触发textbox更改事件并从代码隐藏中保存?txt1.Text=e.Row.DataItem[“TestLbl”]//分配数据源的任何列值我发现错误--无法将[]索引应用于object类型的表达式