问题
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