views:

379

answers:

4

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?

A: 

Greetings, I am facing the same question. Hiding or showing columns will cause my template item (Vertical text containing category name) to disapear. I have debugged and the template item is not updated when hiding columns. At first, the column is hidden. When clicked to show, the template item is updated normallly. When I click to hide the template item is not updated. TIA

A: 

Do you need the GridView to have ViewState? Try turning off ViewState.

<asp:GridView ID="DataGrid1" runat="server" AutoGenerateColumns="false" AllowPaging="True" PageSize="10" GridLines="Horizontal" EnableViewState="false">
James Lawruk
A: 

it will not work

narayanan
+1  A: 

I am also facing the same issue when I delete a column in a GridView from codebehind. When doing so, it will remove all Controls in all ItemTemplates. BoundFields are still intact though.

Can we assume this is a bug in .NET Framework?

Andre Andersen