1
votes

ASP.NET Gridview with Link button column on Dynamic Grid

The ASP.NET Gridview should have a linked column - 1st column, when clicked should take to another page with the clicked cell value. the Grid is a dynamic one, that is the columns are not fixed, no of columns/ column itself is dynamic. I added a asp control just for the first columns and remaining columns are dynamic, in the code behind and I add the first column "linkbutton" always.

<Columns>
    <asp:TemplateField HeaderText="linkbutton">
    <ItemTemplate>
        <asp:LinkButton ID="linkbutton" runat="server" Text='<%#EVal("linkbutton") %>'
            CommandName="ShowDetails" CommandArgument='<%#Eval("linkbutton") %>'>
        </asp:LinkButton>
    </ItemTemplate>
</asp:TemplateField> 
</Columns>

linkbutton is part of the datatable, so when I bind the datatable to gridview it appears twice, once for the templatefield and once from the datatable bind. gridview.column().visible=false didnot work as it considers linkbutton as the only column not the datatable columns.

i tried to add the Linkbutton control from code behind that one also didnt work.

1
Do you have autogeneratecolumns set to true on the GridView? - David Brunow
yes..the autogenerated columns is set to true - Fun Living
Will you show your code behind? If the gridview is dynamic why do you have autogenerated columns? - briskovich
the code behind is simple, get the datatable and bind it. DataTable dt = new DataTable(); dt = ProductDB.GetProductList("1"); GridView1.DataSource = dt; GridView1.DataBind(); - Fun Living

1 Answers

1
votes

I would set the autogeneratecolumns to false, and then use asp:BoundFields in order to show the columns from the datatable, other than the linkbutton, which you are handling with the asp:TemplateField.

You can then use GridView.Columns().Visible to hide/show different columns.

You were not able to use GridView.Columns().Visible with the auto generated columns because they are not added to Columns():

Explicitly declared column fields can be used in combination with automatically generated column fields. When both are used, explicitly declared column fields are rendered first, followed by the automatically generated column fields. Automatically generated column fields are not added to the Columns collection.