最简单的方法是创建自己的GridView继承自
GridView
上课。然后覆盖
CreateChildControls
方法创建新的空表。
这样的做法应该管用:
protected GridViewRow _footerRow2;
protected GridViewRow _headerRow2;
protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
{
// Call base method and get number of rows
int numRows = base.CreateChildControls(dataSource, dataBinding);
if (numRows == 0)
{
//no data rows created, create empty table
//create table
Table table = new Table();
table.ID = this.ID;
//convert the exisiting columns into an array and initialize
DataControlField[] fields = new DataControlField[this.Columns.Count];
this.Columns.CopyTo(fields, 0);
if (this.ShowHeader)
{
//create a new header row
_headerRow2 = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
this.InitializeRow(_headerRow2, fields);
_headerRow2.EnableTheming = true;
table.Rows.Add(_headerRow2);
}
if (this.ShowFooter)
{
//create footer row
_footerRow2 = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
this.InitializeRow(_footerRow2, fields);
_footerRow2.EnableTheming = true;
table.Rows.Add(_footerRow2);
}
this.Controls.Clear();
this.Controls.Add(table);
}
return numRows;
}
基本上,检查GridView是否有任何行,如果没有,则创建页眉行和页脚行(如果已启用)。
编辑:
另外,如果您还想显示空数据文本,可以在创建页眉和页脚之间添加这些行。
GridViewRow emptyRow;
if (this.EmptyDataTemplate != null)
{
emptyRow = this.Controls[0].Controls[0] as GridViewRow;
}
table.Rows.Add(emptyRow);