How to add a GridView Column on code-behind?
Asked Answered
Z

2

11

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>
Z answered 16/5, 2011 at 12:51 Comment(0)
D
16

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
Dispersion answered 16/5, 2011 at 13:2 Comment(3)
Thanks for this, I had the same problem in one program some time ago. Hey, can you with this problem ? #20709457Venus
Why do i get an error like 'The type or namespace GridViewLabelTemplate' could not be found (are you missing a using directive or an assembly reference?) when I try your code?Hoofbound
@KorayDurudogan Check: developer.com/net/asp/article.php/3609991/…Heptad
I
5

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
    }
Ironworker answered 17/10, 2012 at 15:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.