Solution: Show Header/Footer of Gridview with Empty Data Source

Rate It (2)

Last post 10-08-2009 7:03 PM by ledo_moon. 58 replies.

Sort Posts:

  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    02-15-2007, 12:00 AM
    • Member
      8 point Member
    • KiwiPete5
    • Member since 01-17-2007, 10:29 PM
    • Posts 8

    Thanks, this worked a treat for me.

     

    I did change a couple of things that might be useful for others.

    1. I converted it to c# because that's what I'm using.

    2.  My DataTable had some constrains that meant adding an empty row failed so I cleared the contraints before adding the row.

     

    Cheers

    KiwiPete

     

         // ShowGridAlways - Check if the grid is empty. If it is add a dummy row containing the emptyMessage.
        // This forces the header and footer to always be displayed when that is what you want.
        public void ShowGridAlways(ref GridView gridView, ref DataTable dt, string emptyMessage)
        {
            if (dt.Rows.Count == 0)
            {
                // Remove contraints so an empty row can be added.
                dt.Constraints.Clear();
                foreach (DataColumn dc in dt.Columns)
                    dc.AllowDBNull = true;

                // Add a blank row to the dataset
                dt.Columns[0].AllowDBNull = true;
                dt.Rows.Add(dt.NewRow());
                // Bind the DataSet to the GridView
                gridView.DataSource = dt;
                gridView.DataBind();
                // Get the number of columns to know what the Column Span should be
                int columnCount = gridView.Rows[0].Cells.Count;
                // Call the clear method to clear out any controls that you use in the columns.  I use a dropdown list in one of the column so this was necessary.
                gridView.Rows[0].Cells.Clear();
                gridView.Rows[0].Cells.Add(new TableCell());
                gridView.Rows[0].Cells[0].ColumnSpan = columnCount;
                gridView.Rows[0].Cells[0].Text = emptyMessage;
            }
            else
            {
                gridView.DataSource = dt;
                gridView.DataBind();
            }
        }


  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    02-15-2007, 6:16 AM
    • Member
      4 point Member
    • amitavroy
    • Member since 02-15-2007, 10:50 AM
    • Posts 2

    thanks man

    this code came a real bonus to me. i am going to use it in my website.

     

    Regards

    Amitav Roy 

    Regards
    Amitav Roy
    Blog
    Website
    Website
    Filed under:
  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    03-25-2007, 5:50 AM
    • Member
      185 point Member
    • faas1
    • Member since 07-20-2002, 3:40 AM
    • KSA
    • Posts 54

    Hi,

    I am using sqldatasource1 instead of code behind.

    How ccan i solve this??

     ~FAAS

  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    04-08-2007, 11:04 PM
    • Member
      22 point Member
    • JckKerouac
    • Member since 08-03-2002, 9:52 PM
    • Posts 11

    The problem is with the fields declaration - has do with indexing and array length...

    basically: Dim fields As DataControlField() = New DataControlField(Me.Columns.Count - 1) {}

    if you debug the original version, an extra null datacontrolfield is created

     

  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    04-11-2007, 11:27 PM
    • Member
      6 point Member
    • ezeoif0507
    • Member since 01-17-2007, 8:19 AM
    • Posts 4

    I have a work around for the null error that you get in this line:

    Me.InitializeRow(HeaderRow, Fields)

    When you execute this line:

    Dim fields() As System.Web.UI.WebControls.DataControlField = New System.Web.UI.WebControls.DataControlField(Me.Columns.Count) {}

    it adds an additional array element which has a value of "nothing", that is where you get a null ref error.

    I changed this line:

    Dim fields() As System.Web.UI.WebControls.DataControlField = New System.Web.UI.WebControls.DataControlField(Me.Columns.Count) {}
    to

    Dim fields() As System.Web.UI.WebControls.DataControlField=New System.Web.UI.WebControls.DataControlField(Me.Columns.Count-1) {}

    Changing the total columns less 1 fixed having a null array element added to the fields array.

  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    04-23-2007, 1:36 PM
    • Member
      44 point Member
    • r0cky_f
    • Member since 04-19-2007, 5:41 PM
    • Posts 87

    yupz...i'm using the sqldatasource too instead of objectdatasource

    and it seems rather difficult to modify the given solution...since i don't know how to extract sqldatasource's datatable and/or dataset

    anyone knows??

    thx for the help 

  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    04-25-2007, 6:27 AM

    Hi,

        I am using the same solution which was given by CISCBrain earlier, but the problem is that when the MyGridView is being rendered at
    client side, it generates the Client Id as "ctl00_ContentPlaceHolder1_grdShippingItems_grdShippingItems" although I set the ID
    as grdShippingItems only. This way my client side javascript is failing to reference this grid.

       Any Idea, whats going on.

     
    Regards
    Adil



     

  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    06-01-2007, 5:32 PM
    • Member
      61 point Member
    • jmaag
    • Member since 02-21-2007, 5:43 PM
    • Salt Lake City, UT
    • Posts 22

     I've seen a few requests about the SkinID not applying to this grid.  Here's the solution.  Basically, when you create a custom control, the tag no longer is asp:GridView.  Because of this, the asp:GridView skins won't apply to our custom grid.  We need to create a skin specific to our new control.  Below is a sample solution.

      

    <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" Title="Untitled Page" StylesheetTheme="SkinFile" %>
    
    <%@ Register src="MetricControls/MetricDataGraphUC.ascx" TagName="MetricDataGraphUC"
        TagPrefix="uc1" %>
    <%@ Register Namespace="TExtended" TagPrefix="uc2" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
        
    <html xmlns="http://www.w3.org/1999/xhtml" >
        <head id="Head1" runat="server">
            <title>Untitled Page</title>
        </head>
        <body>
            <form id="form1" runat="server">
                <uc2:ExtendedGridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="inventory_request_item_id"
                    DataSourceID="ObjectDataSource1"
                    ShowFooter="True" SkinID="extgridviewSkin" ShowWhenEmpty="True">
                    <Columns>
                        <asp:BoundField DataField="inventory_request_item_id" HeaderText="inventory_request_item_id"
                            ReadOnly="True" SortExpression="inventory_request_item_id" />
                        <asp:BoundField DataField="part_num" HeaderText="part_num" SortExpression="part_num" />
                        <asp:BoundField DataField="part_description" HeaderText="part_description" SortExpression="part_description" />
                        <asp:BoundField DataField="qty_issued" HeaderText="qty_issued" SortExpression="qty_issued" />
                        <asp:BoundField DataField="qty_to_stock" HeaderText="qty_to_stock" SortExpression="qty_to_stock" />
                        <asp:BoundField DataField="return_qty" HeaderText="return_qty" SortExpression="return_qty" />
                        <asp:BoundField DataField="inventory_request_id" HeaderText="inventory_request_id"
                            SortExpression="inventory_request_id" />
                        <asp:BoundField DataField="inventory_return_id" HeaderText="inventory_return_id"
                            SortExpression="inventory_return_id" />
                    </Columns>
                </uc2:ExtendedGridView>
                <asp:ObjectDataSource ID="ObjectDataSource1" runat="server" DataObjectTypeName="System.Guid"
                    DeleteMethod="Delete" InsertMethod="Insert" OldValuesParameterFormatString="original_{0}"
                    SelectMethod="GetInventoryItems" TypeName="ProductionSignalSystemSetTableAdapters.TWeb_InventoryItemTableAdapter"
                    UpdateMethod="Update">
                    <UpdateParameters>
                        <asp:Parameter Name="inventory_request_item_id" Type="Object" />
                        <asp:Parameter Name="part_num" Type="String" />
                        <asp:Parameter Name="part_description" Type="String" />
                        <asp:Parameter Name="qty_issued" Type="Int32" />
                        <asp:Parameter Name="qty_to_stock" Type="Int32" />
                        <asp:Parameter Name="return_qty" Type="Int32" />
                        <asp:Parameter Name="inventory_request_id" Type="Object" />
                        <asp:Parameter Name="inventory_return_id" Type="Object" />
                        <asp:Parameter Name="Original_inventory_request_item_id" Type="Object" />
                    </UpdateParameters>
                    <InsertParameters>
                        <asp:Parameter Name="inventory_request_item_id" Type="Object" />
                        <asp:Parameter Name="part_num" Type="String" />
                        <asp:Parameter Name="part_description" Type="String" />
                        <asp:Parameter Name="qty_issued" Type="Int32" />
                        <asp:Parameter Name="qty_to_stock" Type="Int32" />
                        <asp:Parameter Name="return_qty" Type="Int32" />
                        <asp:Parameter Name="inventory_request_id" Type="Object" />
                        <asp:Parameter Name="inventory_return_id" Type="Object" />
                    </InsertParameters>
                </asp:ObjectDataSource>
            </form>
        </body>
    </html>

     Here's the skin file

      

    <%@ Register Namespace="TExtended" TagPrefix="uc2" %>
    <uc2:ExtendedGridView runat="server" SkinId="extgridviewSkin" BackColor="White" BorderColor="#999999" BorderStyle="Solid" BorderWidth="1px" CellPadding="4" ForeColor="Black" GridLines="Both">
        <FooterStyle BackColor="#8595C5" />
        <RowStyle BackColor="Gainsboro" />
        <SelectedRowStyle BackColor="#FFFFC0" Font-Bold="False" />
        <PagerStyle BackColor="#8595C5" ForeColor="White" HorizontalAlign="Right" />
        <HeaderStyle BackColor="#8595C5" Font-Bold="True" ForeColor="White" />
        <AlternatingRowStyle BackColor="White" />
    </uc2:ExtendedGridView>
     
     The important thing to note here is that you need to register the custom control in the skin file as well as the aspx page.
  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    08-16-2007, 5:39 AM
    • Member
      37 point Member
    • cruster
    • Member since 02-28-2005, 5:38 AM
    • Posts 14
    Awesome! Thanks a lot.
    CISCBrain:
    a more elegant solution, without tempering with the datasource, is creating a custom control that extends GridView and overriding CreateChildControls like so:
     
    protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
    {
        int numRows = base.CreateChildControls(dataSource, dataBinding);
    
        //no data rows created, create empty table if enabled
        if (numRows == 0 && ShowWhenEmpty)
        {
            //create table
            Table table = new Table();
            table.ID = this.ID;
    
            //convert the exisiting columns into an array and initialize
            DataControlField[] fields = new DataControlField[this.Columns.Count];
            this.Columns.CopyTo(fields, 0);
            
            if(this.ShowHeader)
            {
                //create a new header row
                GridViewRow headerRow = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
    
                this.InitializeRow(headerRow, fields);
                table.Rows.Add(headerRow);
            }
    
            //create the empty row
            GridViewRow emptyRow = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
            
            TableCell cell = new TableCell();
            cell.ColumnSpan = this.Columns.Count;
            cell.Width = Unit.Percentage(100);
            if(!String.IsNullOrEmpty(EmptyDataText))
                cell.Controls.Add(new LiteralControl(EmptyDataText));
    
            if(this.EmptyDataTemplate != null)
                EmptyDataTemplate.InstantiateIn(cell);
    
            emptyRow.Cells.Add(cell);
            table.Rows.Add(emptyRow);
            
            if(this.ShowFooter)
            {
                //create footer row
                GridViewRow footerRow = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
    
                this.InitializeRow(footerRow, fields);
                table.Rows.Add(footerRow);
            }
    
            this.Controls.Clear();
            this.Controls.Add(table);
        }
    
        return numRows;
    }
    ShowWhenEmpty is a simple property that you set true to display headers and footers when empty:
    [Category("Behaviour")]
    [Themeable(true)]
    [Bindable(BindableSupport.No)]
    public bool ShowWhenEmpty
    {
        get     
        {
            if (ViewState["ShowWhenEmpty"] == null)
                ViewState["ShowWhenEmpty"] = false;
    
            return (bool)ViewState["ShowWhenEmpty"];
        }
        set
        {
            ViewState["ShowWhenEmpty"] = value;
        }
    }
     With this approach you will have the same formatting for the rows as if the database is not empty. Also, this will display EmptyDataText and EmptyDataTemplate.
  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    09-04-2007, 11:17 AM
    • Contributor
      5,452 point Contributor
    • CSharpSean
    • Member since 10-21-2006, 5:43 AM
    • Orlando, FL
    • Posts 915

    Hello,

    I've used the code above to help extend my gridview to show the footer to allow me to insert a new record, when there is no data. The problem is that I cannt reference the controls in the footer template now. Im using the following:

    ((DropDownList)gvTemp.FooterRow.FindControl("ddlLookup")).SelectedValue;

    Works fine if there is at least one row in the gridview, but as soon as there is no data, the footer shows, but I cannt insert anything anymore I get a  "Object reference not set to an instance of an object."

    TIA!
     

  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    09-04-2007, 1:02 PM
    • Contributor
      5,452 point Contributor
    • CSharpSean
    • Member since 10-21-2006, 5:43 AM
    • Orlando, FL
    • Posts 915
  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    03-26-2008, 11:50 AM
    • Member
      11 point Member
    • andre.monteir
    • Member since 03-05-2008, 2:03 PM
    • Portugal
    • Posts 5

    Nice and clean CISCBrain!!! Yes

    --
    André Monteiro
  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    06-13-2008, 7:10 AM
    • Member
      2 point Member
    • chrisbarm
    • Member since 05-17-2007, 12:46 PM
    • Posts 1

    Hopefully some one can help...  I have been trying now for the past few days to find a button located in the footer of a gridview which has an empty datasource.  I have used the following code to show the header and footer on the empty grid,  but when i try to reference the button to set its visibility to false I get the error "Object reference not set to an instance of an object.".

    Imports System
    Imports System.Collections.Generic
    Imports System.ComponentModel
    Imports System.Text
    Imports System.Web.UI
    Imports System.Web.UI.WebControls
    
    Namespace xGridView
    
        Public Class xGridView
            Inherits GridView
    
    
    #Region "Properties"
    
            <Category("Behaviour")> _
            <Themeable(True)> _
            <Bindable(BindableSupport.No)> _
            <DefaultValue(False)> _
            Public Property ShowWhenEmpty() As Boolean
                Get
                    If ViewState("ShowWhenEmpty") Is Nothing Then
                        Return False
                    End If
    
                    Return CBool(ViewState("ShowWhenEmpty"))
                End Get
                Set(ByVal value As Boolean)
                    ViewState("ShowWhenEmpty") = value
                End Set
            End Property
    
            Protected _footerRow2 As GridViewRow
            Public Overloads Overrides ReadOnly Property FooterRow() As GridViewRow
                Get
                    Dim f As GridViewRow = MyBase.FooterRow
                    If f IsNot Nothing Then
                        Return f
                    Else
                        Return _footerRow2
                    End If
                End Get
            End Property
    
            Protected _headerRow2 As GridViewRow
            Public Overloads Overrides ReadOnly Property HeaderRow() As GridViewRow
                Get
                    Dim h As GridViewRow = MyBase.HeaderRow
                    If h IsNot Nothing Then
                        Return h
                    Else
                        Return Me._headerRow2
                    End If
                End Get
            End Property
    #End Region
    
    
            Protected Overloads Overrides Function CreateChildControls(ByVal dataSource As System.Collections.IEnumerable, ByVal dataBinding As Boolean) As Integer
                Dim numRows As Integer = MyBase.CreateChildControls(dataSource, dataBinding)
    
                'no data rows created, create empty table if enabled 
                If numRows = 0 AndAlso ShowWhenEmpty Then
                    'create table 
                    Dim table As New Table()
                    table.ID = Me.ID
    
                    'convert the exisiting columns into an array and initialize 
                    Dim fields As DataControlField() = New DataControlField(Me.Columns.Count - 1) {}
                    Me.Columns.CopyTo(fields, 0)
    
                    'create a new header row 
                    If Me.ShowHeader Then
                        _headerRow2 = MyBase.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal)
                        Me.InitializeRow(_headerRow2, fields)
                        table.Rows.Add(_headerRow2)
                    End If
    
                    'create the empty row 
                    Dim emptyRow As New GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal)
    
                    Dim cell As New TableCell()
                    cell.ColumnSpan = Me.Columns.Count
                    'cell.Width = Unit.Percentage(100)
                    If Not [String].IsNullOrEmpty(EmptyDataText) Then
                        cell.Controls.Add(New LiteralControl(EmptyDataText))
                    End If
                    If Me.EmptyDataTemplate IsNot Nothing Then
                        EmptyDataTemplate.InstantiateIn(cell)
                    End If
                    emptyRow.Cells.Add(cell)
                    table.Rows.Add(emptyRow)
    
                    'create footer row 
                    If Me.ShowFooter Then
                        _footerRow2 = MyBase.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal)
                        Me.InitializeRow(_footerRow2, fields)
                        table.Rows.Add(_footerRow2)
                    End If
    
                    Me.Controls.Clear()
                    Me.Controls.Add(table)
                End If
    
                Return numRows
            End Function
    
        End Class
    
    End Namespace
     
     
    Thanks
    Chris
  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    06-19-2008, 9:58 AM

    Hello

    I have question as to what is the content of you namespace "TExtended"?

    When I run  form1 Class ExtendedGridView is not a known element, how com?

    I presume "MetricDataGraphUC.ascx" includes namespace TExtended.

    I am looking foward to get the big picture.

    Best regards

    Vilh. Nellemann

  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    07-23-2008, 7:28 AM
    • Member
      2 point Member
    • faruk2011
    • Member since 07-23-2008, 11:20 AM
    • Dhaka, Banglaesh
    • Posts 1

    excellent solution. working properly.

    Thank you very much.

    Faruk Ahmed

    Filed under:
Page 3 of 4 (59 items) < Previous 1 2 3 4 Next >