3

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?

Luke Girvin
  • 13,221
  • 9
  • 64
  • 84
Middletone
  • 4,190
  • 12
  • 53
  • 74
  • Maybe I'm missing something, but... why are there any autogenerated columns when you've set "AutoGenerateColumns" to false? – Andrew Shepherd Aug 09 '09 at 03:42
  • I add them in the code behind myself. For various resons I can't just databind my data to the control and have it create the columsn like you might typically expect.. There is a fair bit of messaging that has to happen first so I basically create he columsn and the parameters for them in my codebehind. – Middletone Aug 09 '09 at 03:58

2 Answers2

1

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
  • 30,112
  • 19
  • 130
  • 137
0

hi solved with visibile=false. on databind .net will not associate values and don t create them on html page

elle0087
  • 840
  • 9
  • 23