根據項目需要,提供自定義服務器控件之 GridViewControl,提供數據為空時的自定義顯示。
[DefaultProperty("EnableEmptyContentRender")]
[ToolboxData("<{0}:GridViewControl runat=server></{0}:GridViewControl>")]
public class GridViewControl : System.Web.UI.WebControls.GridView
{
/// <summary>
/// 是否數據為空時顯示標題行
/// </summary>
private bool _enableEmptyContentRender = true;
/// <summary>
/// 是否數據為空時顯示標題行
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public bool EnableEmptyContentRender
{
set { _enableEmptyContentRender = value; }
get { return _enableEmptyContentRender; }
}
/// <summary>
/// 是否數據為空時顯示標題行
/// </summary>
private string _EmptyDataCellCssClass;
/// <summary>
/// 為空時信息單元格樣式類
/// </summary>
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
public string EmptyDataCellCssClass
{
set { _EmptyDataCellCssClass = value; }
get { return _EmptyDataCellCssClass; }
}
/// <summary>
/// 為空時輸出內容
/// </summary>
/// <param name="writer"></param>
protected virtual void RenderEmptyContent(HtmlTextWriter writer)
{
//Create Header Table
Table tblHeader = new Table();
//Copy All Property
tblHeader.CssClass = this.CssClass;
tblHeader.GridLines = this.GridLines;
tblHeader.BorderStyle = this.BorderStyle;
tblHeader.BorderWidth = this.BorderWidth;
tblHeader.CellPadding = this.CellPadding;
tblHeader.CellSpacing = this.CellSpacing;
tblHeader.HorizontalAlign = this.HorizontalAlign;
tblHeader.Width = this.Width;
tblHeader.CopyBaseAttributes(this);
TableRow rowHeader = new TableRow();
tblHeader.Rows.Add(rowHeader);
rowHeader.CssClass = "TableHeader";
//Generate Table Header
foreach (DataControlField f in this.Columns)
{
TableCell cell = new TableCell();
cell.Text = f.HeaderText;
rowHeader.Cells.Add(cell);
}
TableRow rowBody = new TableRow();
tblHeader.Rows.Add(rowBody);
TableCell cellBody = new TableCell();
cellBody.CssClass = this._EmptyDataCellCssClass;
if (this.EmptyDataTemplate != null)
//the second row, use the template
this.EmptyDataTemplate.InstantiateIn(cellBody);
else
//the second row, use the EmptyDataText
cellBody.Text = this.EmptyDataText;
cellBody.HorizontalAlign = HorizontalAlign.Left;
cellBody.ColumnSpan = this.Columns.Count;
rowBody.Cells.Add(cellBody);
tblHeader.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);
}
}
本文出自 “學習成就夢想” 博客,請務必保留此出處http://qijinchao.blog.51cto.com/1140455/263635