1

i want to show a grid view' header even if the data source that bound to the grid is empty? Is there any way to achieve the same without adding a BLANK row?

Rauf
  • 10,916
  • 19
  • 67
  • 115
  • For what reason you want do like that...showing empty gridview with header alone? – Karthik Ratnam Nov 23 '10 at 14:09
  • 1
    if data source is empty, user have to view a blank space(probable with a text 'No Items Found'). and he/she can not understand it. – Rauf Nov 23 '10 at 14:12
  • I agree. It's sometimes good to display the column headers, even if there is no data. – Jamie Nov 26 '10 at 16:50

2 Answers2

1

As of ASP.NET 4, you can set the ShowHeaderWhenEmpty property of the GridView to true.

Ferruccio
  • 93,779
  • 37
  • 217
  • 294
0

The easiest way would be to create you own GridView inheriting from the GridView class. Then override the CreateChildControls method to create a new empty table.

Something like this should work:

protected GridViewRow _footerRow2;
protected GridViewRow _headerRow2;

protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
{
    // Call base method and get number of rows
    int numRows = base.CreateChildControls(dataSource, dataBinding);

    if (numRows == 0)
    {
        //no data rows created, create empty table
        //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
            _headerRow2 = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);

            this.InitializeRow(_headerRow2, fields);
            _headerRow2.EnableTheming = true;
            table.Rows.Add(_headerRow2);
        }

        if (this.ShowFooter)
        {
            //create footer row
            _footerRow2 = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);

            this.InitializeRow(_footerRow2, fields);
            _footerRow2.EnableTheming = true;
            table.Rows.Add(_footerRow2);
        }

        this.Controls.Clear();
        this.Controls.Add(table);
    }

    return numRows;
}

Basically, you check if the GridView has any rows and if it doesn't then you create the header row and footer row (if they are enabled).

EDIT:

Also, if you wanted to still show your EmptyDataText, you could add these lines inbetween the creating of the header and footer.

GridViewRow emptyRow;

if (this.EmptyDataTemplate != null)
{
     emptyRow = this.Controls[0].Controls[0] as GridViewRow;
}
table.Rows.Add(emptyRow);
Jamie
  • 968
  • 1
  • 11
  • 19