問題:ASP.Net 2.0 中引入的GridView控件當其數據源為空時(GridVIEw.DataSource=null)不能顯示出表頭。
解決:
方法一:采用其EmptyTemplate來實現,模版中寫一個靜態的table;
如果你的表頭只是html的文本,沒有任何控件。你可以在表頭顯示出來的時候,拷貝表頭部分的Html,然後放到EmptyDataTemplate裡面。
缺點: 麻煩,每個GridVIEw都需要設置一下。
方法二: 若數據源為DataTable,則當無數據時,始終返回一個空行的DataTable;
若數據源是集合類(ArrayList,List<T>等),無數據時,生成一個空的實體,加入到集合類中。
缺點: 還是麻煩。
方法三:
也是要給大家介紹的方法: 擴展GridView來實現。繼承GridVIE,重寫Render方法,當其數據源為空時做一下處理,直接看代碼吧:
/// <summary>
/// GridVIEw 擴展控件
/// @author:[email protected]
/// </summary>
public class GridView : System.Web.UI.WebControls.GridVIEw
{
private bool _enableEmptyContentRender = true ;
/// <summary>
/// 是否數據為空時顯示標題行
/// </summary>
public bool EnableEmptyContentRender
{
set { _enableEmptyContentRender = value; }
get { return _enableEmptyContentRender; }
}
private string _EmptyDataCellCSSClass ;
/// <summary>
/// 為空時信息單元格樣式類
/// </summary>
public string EmptyDataCellCSSClass
{
set { _EmptyDataCellCSSClass = value ; }
get { return _EmptyDataCellCSSClass ; }
}
/// <summary>
/// 為空時輸出內容
/// </summary>
/// <param name="writer"></param>
protected virtual void RenderEmptyContent(HtmlTextWriter writer)
{
Table t = new Table(); //create a table
t.CssClass = this.CSSClass; //copy all property
t.GridLines = this.GridLines;
t.BorderStyle = this.BorderStyle;
t.BorderWidth = this.BorderWidth;
t.CellPadding = this.CellPadding;
t.CellSpacing = this.CellSpacing;
t.HorizontalAlign = this.HorizontalAlign;
t.Width = this.Width;
t.CopyBaseAttributes(this);
TableRow row = new TableRow();
t.Rows.Add(row);
foreach (DataControlFIEld f in this.Columns) //generate table header
{
TableCell cell = new TableCell();
cell.Text = f.HeaderText;
cell.CSSClass = "TdHeaderStyle1"; //這裡把表頭樣式寫死了
row.Cells.Add(cell);
}
TableRow row2 = new TableRow();
t.Rows.Add(row2);
TableCell msgCell = new TableCell();
msgCell.CssClass = this._EmptyDataCellCSSClass;
if (this.EmptyDataTemplate != null) //the second row, use the template
{
this.EmptyDataTemplate.InstantiateIn(msgCell);
}
else //the second row, use the EmptyDataText
{
msgCell.Text = this.EmptyDataText;
}
msgCell.HorizontalAlign = HorizontalAlign.Center;
msgCell.ColumnSpan = this.Columns.Count;
row2.Cells.Add(msgCell);
t.RenderControl(writer);
}
protected override void Render(HtmlTextWriter writer)
{
if ( _enableEmptyContentRender && ( this.Rows.Count == 0 || this.Rows[0].RowType == DataControlRowType.EmptyDataRow) )
{
RenderEmptyContent(writer);
}
else
{
base.Render(writer);
}
}
}
}