Click here to Skip to main content
Click here to Skip to main content
Go to top

Show GridView even if datasource is empty

, 8 Feb 2007
Rate this:
Please Sign up or sign in to vote.
A simple method to show a GridView even if the datasource asigned is empty.

Introduction

I was recently faced with a problem where I used a GridView to add new data directly into the grid from the grid's footer, but found out that when there is no data (no rows in my DataTable) to show initially, the grid was not visible, and thus adding new data via the footer was not possible.

Solution Explanation

I wrote a simple method that adds an empty row to the GridView's DataSource then hides that row. Many examples out there shows this technique using the RowDataBound event; it works initially, but when doing a second postback, the empty row and its controls will show up again.

The Code

The method below takes the grid's DataSource and extracts the DataTable from it; it clones a copy and then adds an empty row. Cloning the DataTable will prevent you from adding an empty row inadvertently to your "Master" source.

You will notice two if statements; the first one will execute directly after you have assigned a source to your GridView, the second will execute on Page_Load.

/// =============================================================
/// <summary>
/// Show grid even if datasource is empty
/// <param name="grdView">GridView</param>
/// =============================================================
protected void EmptyGridFix(GridView grdView)
{
    // normally executes after a grid load method
    if (grdView.Rows.Count == 0 &&
        grdView.DataSource != null)
    {
        DataTable dt = null;
        
        // need to clone sources otherwise
        // it will be indirectly adding to 
        // the original source
        
        if (grdView.DataSource is DataSet)
        {
            dt = ((DataSet)grdView.DataSource).Tables[0].Clone();
        }
        else if (grdView.DataSource is DataTable)
        {
            dt = ((DataTable)grdView.DataSource).Clone();
        }

        if (dt == null)
        {
            return;
        }
        
        dt.Rows.Add(dt.NewRow()); // add empty row
        grdView.DataSource = dt;
        grdView.DataBind();        

        // hide row
        grdView.Rows[0].Visible = false;
        grdView.Rows[0].Controls.Clear();
    }

    // normally executes at all postbacks
    if (grdView.Rows.Count == 1 &&
        grdView.DataSource == null)
    {
        bool bIsGridEmpty = true;
        
        // check first row that all cells empty
        for (int i = 0; i < grdView.Rows[0].Cells.Count; i++)
        {
            if (grdView.Rows[0].Cells[i].Text != string.Empty)
            {
                bIsGridEmpty = false;
            }
        }
        // hide row
        if (bIsGridEmpty)
        {
            grdView.Rows[0].Visible = false;
            grdView.Rows[0].Controls.Clear();
        }
    }
}

Implementation

The method must be called on two occasions:

  1. Directly after assigning your DataSet or DataTable to your GridView
  2. On each Page_Load
public class MyPage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        this.EmptyGridFix(grdYourGrid);
        
        if (!this.IsPostBack)
        {
            this.LoadGrid();
        }
    }

    protected void LoadGrid()
    {
        DataSet dsMyDataSet = null;

        // obtain dataset/datatable from DAL/BAL

        grdYourGrid.DataSource = dsMyDataSet.Table[0];
        grdYourGrid.DataBind();

        this.EmptyGridFix(grdYourGrid);
    }

    
    protected void EmptyGridFix(GridView grdView)
    {
        // method code comes here
    }

    // rest of page implementation would follow
}

Last words

The code above only works on instances where the GridView DataSource is being populated via a DataSet or DataTable, I have not tested any other sources.

A good idea is to create a class that would inherit from System.Web.UI.Page and drop the above method in there and have your pages inherit from that class.

I guess there are cleaner/better ways to implement this if... I can think of some really outrageous ways of fixing this stupid problem, like overloading the original GridView control. But one has to weigh the effort spent against the benefits. I really hope to see a fix in future versions of .NET.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Vl@de
Web Developer
South Africa South Africa
My name is Barend Bootha, I'm a C#/Web Developer for a big media firm in South Africa, previously I was involved with financial systems programming and also big CMS's for government contracts.

Comments and Discussions

 
QuestionWorked like a charm! PinmemberFieryPhoenix20126-Mar-13 9:46 
GeneralMy vote of 5 PinmemberInba karthik10-Jan-13 22:42 
QuestionWhat to do in this case if i use DAL method that returns List<ObjectBLL>? Pinmemberx48ray5-Apr-10 6:02 
GeneralUseless PinmemberKbog28-Jan-10 3:43 
GeneralRe: Useless Pinmemberjohnsaxton@yahoo.com9-Mar-10 15:11 
GeneralShow GridView if datasource is empty PinmemberShashikantHadgal9-Feb-09 23:27 
GeneralColumn 'XXXX' does not allow nulls. PinmemberMahir7827-Sep-08 3:49 
GeneralDynamically add a new row to a existing GridView PinmemberSRKVELLANKI19-Sep-08 5:04 
GeneralError in DropDownList SelectedValue Pinmembergustavoadt10-Sep-07 10:09 
GeneralReally its very good... Pinmemberpujari.sreenivas13-Aug-07 0:09 
GeneralCan't seem to set it to work Pinmemberigis17-Jul-07 10:23 
GeneralRe: Can't seem to set it to work Pinmemberkhan_SharePoint21-Nov-07 22:42 
GeneralJust a comment.... PinmemberShirleySW27-Feb-07 12:49 
QuestionWhat about declarative data sources? Pinmemberawarberg17-Feb-07 5:56 
AnswerRe: What about declarative data sources? PinmemberVl@de18-Feb-07 17:44 
QuestionIs this method really needed? Pinmemberilog9-Feb-07 5:19 
AnswerRe: Is this method really needed? Pinmemberilog9-Feb-07 5:23 
GeneralRe: Is this method really needed? Pinmembertxghia589-Feb-07 5:43 
AnswerRe: Is this method really needed? PinmemberVl@de9-Feb-07 17:43 
GeneralRe: Is this method really needed? PinmemberPallavi Bhoite25-Jul-07 19:36 
GeneralRe: Is this method really needed? Pinmemberlvarney4-Feb-09 7:29 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web02 | 2.8.140916.1 | Last Updated 9 Feb 2007
Article Copyright 2007 by Vl@de
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid