代码之家  ›  专栏  ›  技术社区  ›  Rauf

如果没有数据,则网格视图asp.net显示标题

  •  1
  • Rauf  · 技术社区  · 15 年前

    即使绑定到网格的数据源是空的,我也要显示网格视图的头?有没有办法在不添加空白行的情况下实现相同的目的?

    2 回复  |  直到 15 年前
        1
  •  0
  •   Jamie    15 年前

    最简单的方法是创建自己的GridView继承自 GridView 上课。然后覆盖 CreateChildControls 方法创建新的空表。

    这样的做法应该管用:

    protected GridViewRow _footerRow2;
    protected GridViewRow _headerRow2;
    
    protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
    {
        // Call base method and get number of rows
        int numRows = base.CreateChildControls(dataSource, dataBinding);
    
        if (numRows == 0)
        {
            //no data rows created, create empty table
            //create table
            Table table = new Table();
            table.ID = this.ID;
    
            //convert the exisiting columns into an array and initialize
            DataControlField[] fields = new DataControlField[this.Columns.Count];
            this.Columns.CopyTo(fields, 0);
    
            if (this.ShowHeader)
            {
                //create a new header row
                _headerRow2 = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
    
                this.InitializeRow(_headerRow2, fields);
                _headerRow2.EnableTheming = true;
                table.Rows.Add(_headerRow2);
            }
    
            if (this.ShowFooter)
            {
                //create footer row
                _footerRow2 = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
    
                this.InitializeRow(_footerRow2, fields);
                _footerRow2.EnableTheming = true;
                table.Rows.Add(_footerRow2);
            }
    
            this.Controls.Clear();
            this.Controls.Add(table);
        }
    
        return numRows;
    }
    

    基本上,检查GridView是否有任何行,如果没有,则创建页眉行和页脚行(如果已启用)。

    编辑:

    另外,如果您还想显示空数据文本,可以在创建页眉和页脚之间添加这些行。

    GridViewRow emptyRow;
    
    if (this.EmptyDataTemplate != null)
    {
         emptyRow = this.Controls[0].Controls[0] as GridViewRow;
    }
    table.Rows.Add(emptyRow);
    
        2
  •  0
  •   Ferruccio    12 年前

    ShowHeaderWhenEmpty GridView的属性 true .

    推荐文章