0

When I bind data source to GridView, if it has no record in my data source, it will not display anything.

If I set the data to EmptyDataText property in GridView, it will show only that text.

,But I want to show a Column of my data source and the first row must display "No record found" in my GridView. What should I do?

Noppol
  • 69
  • 2
  • 4
  • 10
  • You will need to insert a dummy record in your DataSource or use the EmptyDataTemplate to customize – V4Vendetta Apr 27 '11 at 06:13
  • Check this [link](http://stackoverflow.com/questions/354369/gridview-show-headers-on-empty-data-source) 4.0 has an ShowHeaderWhenEmpty property (i think that's what you want) – V4Vendetta Apr 27 '11 at 06:30

2 Answers2

2

When a datatable is empty, create a new row and and bind after that set columspan to cell count.

        DataTable dtTable = GetData();

        if (dtTable.Rows.Count > 0)
        {
            gvDetails.DataSource = dtTable;
            gvDetails.DataBind();
        }
        else
        {
            dtTable.Rows.Add(dtTable.NewRow());
            gvDetails.DataSource = dtTable;
            gvDetails.DataBind();
            int TotalColumns = gvDetails.Rows[0].Cells.Count;
            gvDetails.Rows[0].Cells.Clear();
            gvDetails.Rows[0].Cells.Add(new TableCell());
            gvDetails.Rows[0].Cells[0].ColumnSpan = TotalColumns;
            gvDetails.Rows[0].Cells[0].Text = "No Record Found";
        }
varadarajan
  • 514
  • 1
  • 3
  • 9
0

You can create an extension method, that would see if no records are there, then add a row, that would say "no records found". For instance like:

your grid.ValidateRecords();

or you can add the extension method at the data source level. For instance like:

public static class Extensions
{
    public static DataSet HasData(this DataSet ds)
    {
        if (ds == null || ds.Tables.Count < 1 || ds.Tables[0].Rows.Count < 1)//add more validation, if dataset is not null?
        {
            DataTable dt = new DataTable("Table1");
            dt.Columns.Add("Col1");
            DataRow dr = dt.NewRow();
            dr["Col1"] = "No records found";
            dt.Rows.Add(dr);
            ds.Tables.Add(dt);
        }
        return ds;
    }

}

Usage:

gridView1.DataSource = myDataSet.HasData();

Output: enter image description here

KMån
  • 9,896
  • 2
  • 31
  • 41