Make GridView footer visible when there is no data bound

荒凉一梦 提交于 2019-12-01 05:56:20

The easiest way to do this is to bind an array with a length of one. You can put anything in it you like to identify that this is a dummy row. On your GridViews RowDataBound method check to see if the data item is the dummy row (make sure the RowType is a DataRow first before trying to check the data). If it is the dummy row set the rows visibility to false. The footer and header should now be showing without any data.

Make sure you set the ShowFooter property to true on your GridView.

eg.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostback)
    {
         myGrid.DataSource = new object[] {null};
         myGrid.DataBind();
    }
}    

protected void myGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        if (e.Row.DataItem == null)
        {
             e.Row.Visible = false;
        }
    }
}

Here's something easy that i've crafted:

    /// <summary>
    /// Ensures that the grid view will contain a footer even if no data exists.
    /// </summary>
    /// <typeparam name="T">Where t is equal to the type of data in the gridview.</typeparam>
    /// <param name="gridView">The grid view who's footer must persist.</param>
    public static void EnsureGridViewFooter<T>(GridView gridView) where T: new()
    {
        if (gridView == null)
            throw new ArgumentNullException("gridView");

        if (gridView.DataSource != null && gridView.DataSource is IEnumerable<T> && (gridView.DataSource as IEnumerable<T>).Count() > 0)
            return;

        // If nothing has been assigned to the grid or it generated no rows we are going to add an empty one.
        var emptySource = new List<T>();
        var blankItem = new T();
        emptySource.Add(blankItem);
        gridView.DataSource = emptySource;

        // On databinding make sure the empty row is set to invisible so it hides it from display.
        gridView.RowDataBound += delegate(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.DataItem == (object)blankItem)
                e.Row.Visible = false;
        };
    }

To Invoke it you may use the following:

        MyGridView.DataSource = data;
        EnsureGridViewFooter<MyDataType>(MyGridView);
        MyGridView.DataBind();

Hope this helps. Cheers!

star

Here is the simple way to show footer when there is empty data in GridView .

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!