How to add a GridView Column on code-behind?

痞子三分冷 提交于 2019-12-12 08:24:16

问题


I'm trying to add a column to a GridView, in ASP.NET 2.0

gridViewPoco.Columns.Add(...)

However, i cant find the right option. I'd like equivalents to the following:

<asp:BoundField>
<asp:TemplateField>

回答1:


For example;

protected void Btn_AddCol_Click(object sender, EventArgs e)
{
    TemplateField tf = new TemplateField();
    tf.HeaderTemplate = new GridViewLabelTemplate(DataControlRowType.Header, "Col1", "Int32");
    tf.ItemTemplate = new GridViewLabelTemplate(DataControlRowType.DataRow, "Col1", "Int32");
    MyGridView.Columns.Add(tf);
}
  • Define new TemplateField
  • Set the column header name (Col1) and type (Int32)
  • Set the column value type (Int32)
  • Add this field to your Gridview



回答2:


Soner's Answer is great for adding columns to the end of the Gridview. If, however, you find yourself needing to add columns to the middle of the GridView, you'll need to take a slightly different path (using the MyGridView.Columns.Insert() function):

  protected void Btn_AddCol_Click(object sender, EventArgs e)
    {
    TemplateField tf = new TemplateField();
    tf.HeaderTemplate = new GridViewLabelTemplate(DataControlRowType.Header, "Col1", "Int32");
    tf.ItemTemplate = new GridViewLabelTemplate(DataControlRowType.DataRow, "Col1", "Int32");
    MyGridView.Columns.Insert(2, tf); //the 2 makes it go into the third column -- zero-based indexing ftw
    }


来源:https://stackoverflow.com/questions/6017670/how-to-add-a-gridview-column-on-code-behind

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!