开发者

How to show "No record found" with Columns in GridView asp.net?

开发者 https://www.devze.com 2023-03-01 03:20 出处:网络
When I bind data source to GridView, if it has no record in my data source, it will not display anything.

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 EmptyDat开发者_C百科aText 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?


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";
        }


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:

How to show "No record found" with Columns in GridView asp.net?

0

精彩评论

暂无评论...
验证码 换一张
取 消