Search code examples
asp.netgridviewpage-init

Dynamic Columns and Data Sources with .NET Grid View


I am working on a multi-purpose page and rather than adding multiple grids to the same page we wanted to use a single GridView to the page, and on Page_Init add the needed columns, and set the respective DataSourceID.

So to do this, we have something like the following in the aspx, the codebehind in the Page_Init is very simple adding a few columns then setting the DataSourceID property of the GridView.

ASPX:

<asp:GridView ID="gvDisplay" runat="server" AutoGenerateColumns="false" CellPadding="5"
    width="100%" AllowPaging="true" PageSize="200" DataSourceID="wuProcessLogDataSource">
    <RowStyle CssClass="RowStyle" />
    <AlternatingRowStyle CssClass="AlternatingRowStyle" />
    <HeaderStyle CssClass="HeaderStyle" />  
</asp:GridView>
<asp:ObjectDataSource id="wuProcessLogDataSource" runat="server" EnablePaging="True" 
    SelectMethod="GetWUProcessLog" TypeName="Project.Objects.WUProcessLogDal"
    SelectCountMethod="GetWUProcessLogTotalRecords">
   <SelectParameters>
    <asp:QueryStringParameter QueryStringField="w" DefaultValue="0" Name="workunitId" />
   </SelectParameters>    
</asp:ObjectDataSource>

The object data source is there and working as the first page load triggers without any issues at all. However, as soon as you click on a page button, the grid disappears from the page? Any ideas?

I would just use a DataGrid but it doesn't have the desired dynamic display abilities for the HyperLinkColumn.


Solution

  • It sounds like you're doing something like

    If (!Page.IsPostBack)
    {
       //create + add columns - set datasource etc
    }
    

    If that's the case - then you need to remove the check and always generate the columns (I'd also suggest disabling viewstate for the datagrid)