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

Rate It (2)

Last post 10-19-2009 1:57 AM by ledo_moon. 59 replies.

Sort Posts:

  • Idea [Idea] Solution: Show Header/Footer of Gridview with Empty Data Source

    02-06-2006, 12:20 AM
    • Member
      40 point Member
    • tmgneuguy
    • Member since 02-06-2006, 4:55 AM
    • Grand Rapids, MI
    • Posts 8
    After coming across the problem regarding not being able to see the header or footer of a GridView when the data source is empty, I have come up with a fairly clean solution (at least IMHO).  I saw a couple other solutions in the forums that gave me some ideas along with an article at http://weblogs.asp.net/despos/archive/2005/06/30/416783.aspx that really got me pointed in the right direction.  The one thing that I wanted to change about the aforementioned link was that no text was displayed to the user.  While you could just add a label above the grid and populate the text property of it when the data source is empty, I prefer to have the error message between the header and footer as I am used to with ASP Classic programming.  The nice thing about this solution is that it doesn't require the stored procedure or retrieval method to return a blank record as I saw in some other solutions.

    I created a sub called BuildNoRecords that goes as follows:

    Public Sub BuildNoRecords(ByVal gridView as GridView, ByVal ds as DataSet)
        Try
           If ds.Tables(0).Rows.Count = 0 Then
              'Add a blank row to the dataset
              ds.Tables(0).Rows.Add(ds.Tables(0).NewRow())
              'Bind the DataSet to the GridView
              gridView.DataSource = ds
              gridView.DataBind()
              'Get the number of columns to know what the Column Span should be
              Dim columnCount as Integer = 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 = "No Records Found."
           End If
        Catch ex as Exception
           'Do your exception handling here
        End Try
    End Sub

    I then call this sub after I fill my DataSet:

    Dim ds as DataSet = Nothing
    ds = obj.GetList()
    'Call the Sub: gv is the GridView I have designed in the form designer.
    BuildNoRecords(gv, ds)


    I hope that this helps others who have had the same problem I did.
  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    02-08-2006, 7:32 AM
    • Member
      40 point Member
    • tmgneuguy
    • Member since 02-06-2006, 4:55 AM
    • Grand Rapids, MI
    • Posts 8
    I accidentally left out a relatively key part of the code... oops!

    The main If block "If ds.Tables(0).Rows.Count = 0 Then" needs to have a Else statement for when the data source has records.  It should read like this:

            If ds.Tables(0).Rows.Count = 0 Then
              'Add a blank row to the dataset
              ds.Tables(0).Rows.Add(ds.Tables(0).NewRow())
              'Bind the DataSet to the GridView
              gridView.DataSource = ds
              gridView.DataBind()
              'Get the number of columns to know what the Column Span should be
              Dim columnCount as Integer = 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 = "No Records Found."
           Else
              gridView.DataSource = ds
              gridView.DataBind()
           End If

    Sorry for any confusion.
  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    05-26-2006, 5:00 PM
    • Member
      125 point Member
    • TonyS
    • Member since 12-09-2005, 5:53 AM
    • Posts 25

    I have a question I am trying to incorporate this into my app and I am not sure what to use for the term obj in the line

     

    ds = obj.GetList()

     

    Can you please clarify?

     

    Thanks

     

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

    06-28-2006, 11:03 AM
    • Member
      190 point Member
    • DonalDorling
    • Member since 05-14-2006, 11:47 PM
    • Posts 38
    Can any one help with "ds = obj.GetList()" that line of code please

    Thanks

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

    06-28-2006, 10:24 PM
    • Member
      319 point Member
    • FrenchiInLA
    • Member since 03-30-2005, 8:00 PM
    • Huntington Beach, CA
    • Posts 94

    "ds = obj.GetList()"  is a methid in its application that return a Dataset. in your case you should provide The dataSet that your GridView is Bind to it.

     

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

    07-26-2006, 3:58 AM
    • Member
      97 point Member
    • CISCBrain
    • Member since 09-15-2004, 9:56 AM
    • Posts 22
    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

    07-26-2006, 10:43 AM
    • Member
      35 point Member
    • OblivionSY
    • Member since 07-26-2006, 2:32 PM
    • Posts 14
    Hi,

    I have converted this to VB.net (2.0) and get an error on the
    this.InitializeRow(headerRow, fields);

    or me.InitializeRow(headerRow, fields) as the VB i get an Object reference not set to an instance of an object error.Fields and headerRow are both something so i presume it is a property on one of those objects which is causing the problem? Have you come accross this, any thoughts?
    Cheers

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

    07-26-2006, 10:58 AM
    • Member
      97 point Member
    • CISCBrain
    • Member since 09-15-2004, 9:56 AM
    • Posts 22
    please post your code here as there's no way to see what may cause the error.
  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    07-26-2006, 12:10 PM
    • Member
      35 point Member
    • OblivionSY
    • Member since 07-26-2006, 2:32 PM
    • Posts 14
    here is the code - it has not been tested as the Me.InitializeRow(HeaderRow, Fields) line fails.

    Also worth noting that i had trouble converting this line:
                    Dim fields() As System.Web.UI.WebControls.DataControlField = New System.Web.UI.WebControls.DataControlField(Me.Columns.Count) {}

    and used an online c# converter, but least it compiles now? hopefully it is correct!



    Dim
    NumRows As Integer = MyBase.CreateChildControls(dataSource, dataBinding)
                If NumRows = 0 AndAlso ShowWhenEmpty Then
                    Dim T As New System.Web.UI.WebControls.Table
                    T.ID = Me.ID

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

                    '//convert the exisiting columns into an array and initialize
                    'DataControlField[] fields = new DataControlField[this.Columns.Count];
                    'this.Columns.CopyTo(fields, 0);

                    If Me.ShowHeader Then
                        Dim HeaderRow As System.Web.UI.WebControls.GridViewRow = MyBase.CreateRow(-1, -1, Web.UI.WebControls.DataControlRowType.Header, Web.UI.WebControls.DataControlRowState.Normal)
                        Me.InitializeRow(HeaderRow, Fields)
                        T.Rows.Add(HeaderRow)
                    End If

                    'Create Empty Row
                    Dim EmptyRow As New System.Web.UI.WebControls.GridViewRow(-1, -1, Web.UI.WebControls.DataControlRowType.EmptyDataRow, Web.UI.WebControls.DataControlRowState.Normal)
                    Dim Cell As New System.Web.UI.WebControls.TableCell
                    Cell.ColumnSpan = Me.Columns.Count
                    Cell.Width = System.Web.UI.WebControls.Unit.Percentage(100)
                    If Not System.String.IsNullOrEmpty(EmptyDataText) Then
                        Dim Lit As New System.Web.UI.WebControls.Literal
                        Lit.Text = Me.EmptyDataText
                        Cell.Controls.Add(Lit)
                    End If
                    If Not Me
    .EmptyDataTemplate Is Nothing Then
                        Me.EmptyDataTemplate.InstantiateIn(Cell)
                    End If
                    EmptyRow.Cells.Add(Cell)
                    T.Rows.Add(EmptyRow)

                    'Create footer row
                    Dim FooterRow As System.Web.UI.WebControls.GridViewRow
                    FooterRow = MyBase.CreateRow(-1, -1, Web.UI.WebControls.DataControlRowType.Footer, Web.UI.WebControls.DataControlRowState.Normal)
                    Me.InitializeRow(FooterRow, Fields)
                    T.Rows.Add(FooterRow)
                    Me.Controls.Clear()
                    Me.Controls.Add(T)

                    Return NumRows

                End If

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

    07-27-2006, 11:00 AM
    • Member
      45 point Member
    • drodrig
    • Member since 05-09-2006, 10:05 AM
    • Spain
    • Posts 9

    This code work fine to show ViewGrid, but when I access to FooterRow or HeaderRow properties after all page has loaded, I get a null reference.

    Do you know why?

    Thank you

    drodrig

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

    07-27-2006, 11:25 AM
    • Member
      97 point Member
    • CISCBrain
    • Member since 09-15-2004, 9:56 AM
    • Posts 22
    Do you have something in the footer and header ?
  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    07-28-2006, 6:23 AM
    • Member
      35 point Member
    • OblivionSY
    • Member since 07-26-2006, 2:32 PM
    • Posts 14
    The trouble i had was in this section

                    If Me.ShowHeader Then
                        Dim HeaderRow As System.Web.UI.WebControls.GridViewRow = MyBase.CreateRow(-1, -1, Web.UI.WebControls.DataControlRowType.Header, Web.UI.WebControls.DataControlRowState.Normal)
                        Me.InitializeRow(HeaderRow, Fields)
                        T.Rows.Add(HeaderRow)
                    End If

    the Me.Initialize row caused an error. Also controls within the datagrid stopped firing their events. I have a custom control there with about 8 buttos doing various things to the listed record based on its ID. When the buttons are clicked, the page refreshes but their click even is not fired.
  • Re: Solution: Show Header/Footer of Gridview with Empty Data Source

    07-28-2006, 6:42 AM
    • Member
      45 point Member
    • drodrig
    • Member since 05-09-2006, 10:05 AM
    • Spain
    • Posts 9

    I talk about CISCBrain is not online. Last active: 07-28-2006, 2:48 AM CISCBrain  C# code.

    Yes I have normal headers (titles) and custom Footer (for Insert methods), I haven't custom controls, just DropDownList and Button.

    All is painted well, but HeaderRow and FooterRow are null, and I cant access to control values for the insert method.

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

    07-28-2006, 6:48 AM
    • Member
      45 point Member
    • drodrig
    • Member since 05-09-2006, 10:05 AM
    • Spain
    • Posts 9
    drodrig:

    I talk about CISCBrain is not online. Last active: 07-28-2006, 2:48 AM CISCBrain  C# code.

    Yes I have normal headers (titles) and custom Footer (for Insert methods), I haven't custom controls, just DropDownList and Button.

    All is painted well, but HeaderRow and FooterRow are null, and I cant access to control values for the insert method.

    my code is here http://forums.asp.net/thread/1352925.aspx

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

    07-28-2006, 7:57 AM
    • Member
      97 point Member
    • CISCBrain
    • Member since 09-15-2004, 9:56 AM
    • Posts 22
    I think I fixed the header/footer rows being null. Just add these to the class:
     
            protected GridViewRow _footerRow2;
            public override GridViewRow FooterRow
            {
                get
                {
                    GridViewRow f = base.FooterRow;
                    if(f != null)
                        return f;
                    else
                        return _footerRow2;
                }
            }
    
            protected GridViewRow _headerRow2;
            public override GridViewRow HeaderRow
            {
                get
                {
                    GridViewRow h = base.HeaderRow;
                    if(h != null)
                        return h;
                    else
                        return this._headerRow2;
                }
            }
     and modify CreateChildControls like so:
    .
    .    //create a new header row
        _headerRow2 = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
    
        this.InitializeRow(_headerRow2, fields);
        table.Rows.Add(_headerRow2);
    .
    .
    .
        //create footer row
        _footerRow2 = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
    
        this.InitializeRow(_footerRow2, fields);
        table.Rows.Add(_footerRow2);
    .
    .
    
     P.S. : I have private fields and non-virtual methods :((
Page 1 of 4 (60 items) 1 2 3 4 Next >