动态添加带有ItemTemplate的列到Grid-view

3

我想知道如何动态地向GridView添加列。GridView应该接受用户输入。我知道如何为特定的列数使用ItemTemplate,但我不知道如何动态添加带有ItemTemplate(文本框)字段的列并进行数据绑定。

1个回答

6

您需要创建一个实现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进行绑定并添加新行呢? - user2358851
使用RowDataBound事件为动态添加的控件分配值,发布的答案已相应编辑。 - Anubrij Chandra
如何从代码后台触发文本框更改事件并保存? - immayankmodi
txt1.Text = e.Row.DataItem["TestLbl"]; //为您的数据源分配任何列值。我遇到了错误--无法将[]应用于类型为object的表达式。 - RyanN1220

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接