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

左心房为你撑大大i 提交于 2020-01-06 09:05:35

问题


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?


回答1:


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



回答2:


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:



来源:https://stackoverflow.com/questions/5800097/how-to-show-no-record-found-with-columns-in-gridview-asp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!