Click here to Skip to main content
15,867,704 members
Articles / Web Development / ASP.NET

Show GridView even if datasource is empty

Rate me:
Please Sign up or sign in to vote.
3.21/5 (17 votes)
8 Feb 2007CPOL2 min read 173K   36   21
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.

C#
/// =============================================================
/// <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
C#
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)


Written By
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! Pin
FieryPhoenix20126-Mar-13 9:46
FieryPhoenix20126-Mar-13 9:46 
GeneralMy vote of 5 Pin
Inba karthik10-Jan-13 22:42
Inba karthik10-Jan-13 22:42 
QuestionWhat to do in this case if i use DAL method that returns List<ObjectBLL>? Pin
Pavel Yermalovich5-Apr-10 6:02
Pavel Yermalovich5-Apr-10 6:02 
GeneralUseless Pin
Kbog28-Jan-10 3:43
Kbog28-Jan-10 3:43 
GeneralRe: Useless Pin
User 7537519-Mar-10 15:11
User 7537519-Mar-10 15:11 
GeneralShow GridView if datasource is empty Pin
ShashikantHadgal9-Feb-09 23:27
ShashikantHadgal9-Feb-09 23:27 
GeneralColumn 'XXXX' does not allow nulls. Pin
Mahir7827-Sep-08 3:49
Mahir7827-Sep-08 3:49 
GeneralDynamically add a new row to a existing GridView Pin
SRKVELLANKI19-Sep-08 5:04
SRKVELLANKI19-Sep-08 5:04 
GeneralError in DropDownList SelectedValue Pin
gustavoadt10-Sep-07 10:09
gustavoadt10-Sep-07 10:09 
GeneralReally its very good... Pin
pujari.sreenivas13-Aug-07 0:09
pujari.sreenivas13-Aug-07 0:09 
GeneralCan't seem to set it to work Pin
igis17-Jul-07 10:23
igis17-Jul-07 10:23 
GeneralRe: Can't seem to set it to work Pin
khan SharePoint Developer21-Nov-07 22:42
khan SharePoint Developer21-Nov-07 22:42 
GeneralJust a comment.... Pin
ShirleySW27-Feb-07 12:49
ShirleySW27-Feb-07 12:49 
QuestionWhat about declarative data sources? Pin
awarberg17-Feb-07 5:56
awarberg17-Feb-07 5:56 
AnswerRe: What about declarative data sources? Pin
Vl@de18-Feb-07 17:44
Vl@de18-Feb-07 17:44 
QuestionIs this method really needed? Pin
ilog.km9-Feb-07 5:19
ilog.km9-Feb-07 5:19 
AnswerRe: Is this method really needed? Pin
ilog.km9-Feb-07 5:23
ilog.km9-Feb-07 5:23 
GeneralRe: Is this method really needed? Pin
txghia589-Feb-07 5:43
txghia589-Feb-07 5:43 
AnswerRe: Is this method really needed? Pin
Vl@de9-Feb-07 17:43
Vl@de9-Feb-07 17:43 
That is a way to do it yes, and I have done that in other projects.

But my situation on this project is different... All adding/editing must happening on the grid it self, thus I needed a way to display the grid at all times. Smile | :)
GeneralRe: Is this method really needed? Pin
Pallavi Bhoite25-Jul-07 19:36
Pallavi Bhoite25-Jul-07 19:36 
GeneralRe: Is this method really needed? Pin
lvarney4-Feb-09 7:29
lvarney4-Feb-09 7:29 

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

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