2015年7月14日16:50:06 Gridview 默认展示数据时,若数据为空,则表格不显示,显示不美观。
针对此问题进行扩展:
using System.Web.UI.WebControls; public static class GridViewExtension { public static void BindEmptyData(this GridView g) { if (g.Rows.Count == 0) { //表头的设置 GridViewRow row = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal); foreach (DataControlField field in g.Columns) { TableCell cell = new TableCell(); cell.Text = field.HeaderText; cell.Width = field.HeaderStyle.Width; cell.Height = field.HeaderStyle.Height; cell.ForeColor = field.HeaderStyle.ForeColor; cell.Font.Size = field.HeaderStyle.Font.Size; cell.Font.Bold = field.HeaderStyle.Font.Bold; cell.Font.Name = field.HeaderStyle.Font.Name; cell.Font.Strikeout = field.HeaderStyle.Font.Strikeout; cell.Font.Underline = field.HeaderStyle.Font.Underline; cell.BackColor = field.HeaderStyle.BackColor; cell.VerticalAlign = field.HeaderStyle.VerticalAlign; cell.HorizontalAlign = field.HeaderStyle.HorizontalAlign; cell.CssClass = field.HeaderStyle.CssClass; cell.BorderColor = field.HeaderStyle.BorderColor; cell.BorderStyle = field.HeaderStyle.BorderStyle; cell.BorderWidth = field.HeaderStyle.BorderWidth; row.Cells.Add(cell); } TableItemStyle headStyle = g.HeaderStyle; TableItemStyle emptyStyle = g.EmptyDataRowStyle; emptyStyle.Width = headStyle.Width; emptyStyle.Height = headStyle.Height; emptyStyle.ForeColor = headStyle.ForeColor; emptyStyle.Font.Size = headStyle.Font.Size; emptyStyle.Font.Bold = headStyle.Font.Bold; emptyStyle.Font.Name = headStyle.Font.Name; emptyStyle.Font.Strikeout = headStyle.Font.Strikeout; emptyStyle.Font.Underline = headStyle.Font.Underline; emptyStyle.BackColor = headStyle.BackColor; emptyStyle.VerticalAlign = headStyle.VerticalAlign; emptyStyle.HorizontalAlign = headStyle.HorizontalAlign; emptyStyle.CssClass = headStyle.CssClass; emptyStyle.BorderColor = headStyle.BorderColor; emptyStyle.BorderStyle = headStyle.BorderStyle; emptyStyle.BorderWidth = headStyle.BorderWidth; //空白行的设置 GridViewRow row1 = new GridViewRow(0, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal); TableCell cell1 = new TableCell(); cell1.Text = "没有任何数据可以显示"; cell1.ForeColor = System.Drawing.Color.Purple; cell1.BackColor = System.Drawing.Color.White; row1.Cells.Add(cell1); cell1.ColumnSpan = g.Columns.Count; if (g.Controls.Count == 0) { g.Page.Response.Write("<script language='javascript'>alert('请先调用GridView的BindData()方法后 调用此扩展方法!');</script>"); } else { g.Controls[0].Controls.Clear(); g.Controls[0].Controls.AddAt(0, row); g.Controls[0].Controls.AddAt(1, row1); } } } }
代码调用方式如下:
protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindData(); } } protected void BindData() { this.grid_PlantVarietyRight.DataBind(); this.grid_PlantVarietyRight.BindEmptyData(); }
显示效果如下图
本扩展主要参考 http://www.cnblogs.com/muer/archive/2010/03/26/1697178.html 稍作扩展,感谢这位哥。