根据项目需要,提供自定义服务器控件之 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