转载:GridView 空记录时显示 Header
地址:http://www.star1168.com/blog/index.php/archives/158
public class GridViewEx : GridView
{
// 用于保存 Columns 中列
private ArrayList _columns;
[DefaultValue(true)]
public bool ForceShowHeader
{
get
{
object o = ViewState["ForceShowHeader"];
if (o != null)
return (bool)o;
return true;
}
set
{
ViewState["ForceShowHeader"] = value;
}
}
protected override ICollection CreateColumns(PagedDataSource dataSource, bool useDataSource)
{
if (_columns != null)
return _columns;
_columns = (ArrayList)base.CreateColumns(dataSource, useDataSource);
return _columns;
}
protected override int CreateChildControls(IEnumerable dataSource, bool dataBinding)
{
int count = base.CreateChildControls(dataSource, dataBinding);
if (ForceShowHeader && count == 0)
{
Table table;
if (Controls.Count == 0)
{
table = CreateChildTable();
Controls.Add(table);
}
else
{
table = Controls[0] as Table;
if (table == null)
throw new ApplicationException("第一个子控件不为 Table 控件");
}
DataControlField[] fields = new DataControlField[_columns.Count];
_columns.CopyTo(fields, 0);
// 创建表示头并初始化此行
GridViewRow headerRow = CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
InitializeRow(headerRow, fields);
// 引发 RowCreated 事件
GridViewRowEventArgs args = new GridViewRowEventArgs(headerRow);
OnRowCreated(args);
// 把表头行添加到表格中
table.Rows.AddAt(0, headerRow);
}
return count;
}
}
在使用的时候,把 ForceShowHeader 属性设置为 true 即可(默认值是 true