Gridview looses ItemTemplate after columns are removed

Posted by Middletone on Stack Overflow See other posts from Stack Overflow or by Middletone
Published on 2009-08-09T03:25:45Z Indexed on 2010/05/21 12:50 UTC
Read the original article Hit count: 236

Filed under:
|
|
|

I'm trying to bind a datatable to a gridview where I've removed some of the autogenerated columns in the code behind.

I've got two template columns and it seems that when I alter the gridview in code behind and remove the non-templated columns that the templates loose the controls that are in them.

Using the following as a sample, "Header A" will continue to be visible but "Header B" will dissapear after removing any columsn that are located at index 2 and above. I'm creating columns in my codebehind for the grid as a part of a reporting tool. If I don't remove the columns then there doesn't seem to be an issue.

<asp:GridView ID="DataGrid1" runat="server" AutoGenerateColumns="false" AllowPaging="True" PageSize="10" GridLines="Horizontal">
    <Columns>
        <asp:TemplateField HeaderText="Header A"  >
            <ItemTemplate >
                  Text A
            </ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField>
            <HeaderTemplate>
                      Header B
            </HeaderTemplate>
            <ItemTemplate>
                      Text B
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

For i = 2 To DataGrid1.Columns.Count - 1
      DataGrid1.Columns.RemoveAt(2)
Next

EDIT

So from what I've read this seems to be a problem that occurs when the grid is altered. Does anyone know of a good workaround to re-initialize the template columns or set them up again so that when the non-template columns are removed that hte templates don't get removed as well?

© Stack Overflow or respective owner

Related posts about ASP.NET

Related posts about gridview