始终显示FooterTemplate,即使没有数据。

8
有没有一种简单的方法可以使 GridView 中的 FooterTemplate 始终可见,即使 DataSource 为空?

你为什么想要实现这个? - Muhammad Akhtar
请看我对下面的评论,我解释了我需要它做什么。 - Shimmy Weitzhandler
3个回答

7

我也曾遇到这样的问题。来自Alconja的链接非常有帮助(感谢Alconja),但GridView.FooterRow返回null,而我需要它来从页脚插入新记录。

这是我最终可行的解决方案。现在即使网格为空,您也可以从页脚插入数据。

GridViewExtended.cs(位于App_Code文件夹中的一个类):

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace YourNamespace
{

  public class GridViewExtended : GridView
  {
    #region Public Properties
    [Category("Behavior")]
    [Themeable(true)]
    [Bindable(BindableSupport.No)]
    public bool ShowFooterWhenEmpty
    {
      get
      {
        if (this.ViewState["ShowFooterWhenEmpty"] == null)
        {
          this.ViewState["ShowFooterWhenEmpty"] = false;
        }

        return (bool)this.ViewState["ShowFooterWhenEmpty"];
      }
      set
      {
        this.ViewState["ShowFooterWhenEmpty"] = value;
      }
    }
    #endregion

    private GridViewRow _footerRow2;
    public override GridViewRow FooterRow
    {
      get
      {
        GridViewRow f = base.FooterRow;
        if (f != null)
          return f;
        else
          return _footerRow2;
      }
    }

    protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
    {
      int rows = base.CreateChildControls(dataSource, dataBinding);

      //  no data rows created, create empty table if enabled
      if (rows == 0 && (this.ShowFooterWhenEmpty))
      {
        //  create the table
        Table table = this.CreateChildTable();

        DataControlField[] fields;
        if (this.AutoGenerateColumns)
        {
          PagedDataSource source = new PagedDataSource();
          source.DataSource = dataSource;

          System.Collections.ICollection autoGeneratedColumns = this.CreateColumns(source, true);
          fields = new DataControlField[autoGeneratedColumns.Count];
          autoGeneratedColumns.CopyTo(fields, 0);
        }
        else
        {
          fields = new DataControlField[this.Columns.Count];
          this.Columns.CopyTo(fields, 0);
        }

        if (this.ShowHeaderWhenEmpty)
        {
          //  create a new header row
          GridViewRow headerRow = base.CreateRow(-1, -1, DataControlRowType.Header, DataControlRowState.Normal);
          this.InitializeRow(headerRow, fields);

          //  add the header row to the table
          table.Rows.Add(headerRow);
        }

        //  create the empty row
        GridViewRow emptyRow = new GridViewRow(-1, -1, DataControlRowType.EmptyDataRow, DataControlRowState.Normal);
        TableCell cell = new TableCell();
        cell.ColumnSpan = fields.Length;
        cell.Width = Unit.Percentage(100);

        //  respect the precedence order if both EmptyDataTemplate
        //  and EmptyDataText are both supplied ...
        if (this.EmptyDataTemplate != null)
        {
          this.EmptyDataTemplate.InstantiateIn(cell);
        }
        else if (!string.IsNullOrEmpty(this.EmptyDataText))
        {
          cell.Controls.Add(new LiteralControl(EmptyDataText));
        }

        emptyRow.Cells.Add(cell);
        table.Rows.Add(emptyRow);

        if (this.ShowFooterWhenEmpty)
        {
          //  create footer row
          _footerRow2 = base.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal);
          this.InitializeRow(_footerRow2, fields);

          //  add the footer to the table
          table.Rows.Add(_footerRow2);
        }

        this.Controls.Clear();
        this.Controls.Add(table);
      }

      return rows;
    }
  }

}

aspx 页面中,只需添加:
<%@ Register TagPrefix="YourPrefix" Namespace="YourNamespace" %>

<asp:GridView替换为<YourPrefix:GridViewExtended

希望对某些人有所帮助。


我尝试这样做是因为我有一个带有页脚的GridView,可以添加新记录。用户必须单击页脚上的“添加新项”按钮,然后才能看到添加新行的控件。但是这段代码并没有按预期工作(您可能需要用代码替换对base.CreateChildControls的调用,并设置id等)。 - Tahir Hassan
1
对我来说,这个解决方案的问题在于当网格为空时,页脚的RowDataBound事件出现某些原因无法触发。由于我需要填充一些下拉框,这是一个致命的缺陷。 - see sharper
太棒了!谢谢! - Tikhon
ShowFooterWhenEmpty="True" - Mina Gabriel

5

我并不在意使用Html,问题是我想让列宽适应GridView的列宽度。 当数据存在时,我希望它显示一些摘要,并在项目模板上按下“新建”按钮时插入一个项目(我已经在页脚中实现了,你知道我的意思吗?),或者始终显示页脚。 换句话说: *有没有办法调用显示页脚(当没有数据时)? *这个空数据行到底是什么,没明白(我正在使用EntityDataSource,我认为这可能会更加复杂或根本不可能)。 谢谢伙计。 - Shimmy Weitzhandler
我不想使用空行,如果没有虚拟数据,我可以子类化GridView。你有什么建议吗? - Shimmy Weitzhandler
1
我包含的第二个链接(http://mattberseth.com/blog/2007/07/how%5Fto%5Fshow%5Fheader%5Fand%5Ffooter.html)包含一些示例代码,可以让您拥有一个具有ShowFooterWhenEmpty属性的网格。 - Alconja

3
作为之前评论者所提到的,RowDataBound事件不会对页脚触发。我找到了另一个代码片段解决了这个问题,但除了显示页脚外,它还显式地创建行(触发RowCreated事件)并绑定它(触发RowDataBound事件)。
我已经使用代码转换器将上述引用代码转换为C#并进行了一些微小的修改。我还包括了我在分解代码时做出的注释。现在RowCreated和RowDataBound事件正在触发,我能够在页脚中填充下拉菜单。
    using System.Linq;
    using System.Web.UI.WebControls;
    using System.ComponentModel;

    namespace WebUI.Controls
    {
        //modified from https://dev59.com/1HA75IYBdhLWcg3wKluM
        public class GridViewExtended : GridView
        {

            private GridViewRow _footerRow;
            [DefaultValue(false), Category("Appearance"), Description("Include the footer when the table is empty")]
            public bool ShowFooterWhenEmpty { get; set; }

            [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden), Browsable(false)]
            public override GridViewRow FooterRow {
                get {
                    if ((this._footerRow == null)) {
                        this.EnsureChildControls();
                    }
                    return this._footerRow;
                }
            }

            protected override int CreateChildControls(System.Collections.IEnumerable dataSource, bool dataBinding)
            {
                //creates all the rows that would normally be created when instantiating the grid
                int returnVal = base.CreateChildControls(dataSource, dataBinding);
                //if no rows were created (i.e. returnVal == 0), and we need to show the footer row, then we need to create and bind the footer row.
                if (returnVal == 0 && this.ShowFooterWhenEmpty) {
                    Table table = this.Controls.OfType<Table>().First<Table>();
                    DataControlField[] dcf = new DataControlField[this.Columns.Count];
                    this.Columns.CopyTo(dcf, 0);
                    //creates the footer row
                    this._footerRow = this.CreateRow(-1, -1, DataControlRowType.Footer, DataControlRowState.Normal, dataBinding, null, dcf, table.Rows, null);
                    if (!this.ShowFooter) {
                        _footerRow.Visible = false;
                    }
                }
                return returnVal;
            }

            private GridViewRow CreateRow(int rowIndex, int dataSourceIndex, DataControlRowType rowType, DataControlRowState rowState, bool dataBind, object dataItem, DataControlField[] fields, TableRowCollection rows, PagedDataSource pagedDataSource)
            {
                GridViewRow row = this.CreateRow(rowIndex, dataSourceIndex, rowType, rowState);
                GridViewRowEventArgs e = new GridViewRowEventArgs(row);
                if ((rowType != DataControlRowType.Pager)) {
                    this.InitializeRow(row, fields);
                } else {
                    this.InitializePager(row, fields.Length, pagedDataSource);
                }
                //if the row has data, sets the data item
                if (dataBind) {
                    row.DataItem = dataItem;
                }
                //Raises the RowCreated event
                this.OnRowCreated(e);
                //adds the row to the gridview's row collection
                rows.Add(row);
                //explicitly binds the data item to the row, including the footer row and raises the RowDataBound event.
                if (dataBind) {
                    row.DataBind();
                    this.OnRowDataBound(e);
                    row.DataItem = null;
                }
                return row;
            }

        }

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接